0

I want to be able to declare a variable in a shell script and use it in a ruby inline command. Something like this:

foo=kroe761
bar=$(ruby -e 'puts $foo')
echo My name is $bar

$ My name is kroe761.

But, what I get is My name is. How can I get shell variables into my ruby script?

2
  • Parameter expansion does not happen in the string enclosed in apostrophes. The Ruby code you run is exactly puts $foo and, because its name starts with $, $foo is an uninitialized global variable and the Ruby program does not output anything (it outputs an empty line but the newline is trimmed by $()). Commented Jul 20, 2021 at 16:40
  • Building the Ruby program in the command line this way is not the right way to do it (and doing it right it's not as easy as it seems). I suggest you to pass $foo as an argument to the script in the command line and use the global variable ARGV to retrieve it in the program. Something like ruby -e 'puts ARGV[0]' "$foo". It is very important to put $foo between quotes, otherwise, if it contains spaces, it is not passed to ruby as one argument but the shell splits by spaces into multiple arguments. Commented Jul 20, 2021 at 16:48

1 Answer 1

2

Your program does not work because the parameter expansion in the command line does not happen in the strings enclosed in apostrophes.

The Ruby code you run is exactly puts $foo and, because its name starts with $, for the Ruby code $foo is an uninitialized global variable. The Ruby program outputs an empty line but the newline is trimmed by $() and the final value stored in the shell variable bar is an empty string.

If you try ruby -e "puts $foo" (because the parameters are expanded between double quotes) you'll find out that it also does not produce what you want but, even more, it throws an error. The Ruby code it executes is puts kroe761 and it throws because kroe761 is an unknown local variable or method name.
Building the Ruby program in the command line this way is not the right way to do it (and doing it right it's not as easy as it seems).

I suggest you to pass the value of $foo as an argument to the script in the command line and use the global variable ARGV in the Ruby code to retrieve it.

foo=kroe761
bar=$(ruby -e 'puts ARGV[0]' "$foo")
echo "My name is $bar"

It is very important to put $foo between quotes, otherwise, if it contains spaces, it is not passed to ruby as one argument but the shell splits it by spaces into multiple arguments.

Check it online.

Sign up to request clarification or add additional context in comments.

1 Comment

Super helpful! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.