Reputation: 3534
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?
Upvotes: 0
Views: 1075
Reputation: 72425
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.
Upvotes: 2