0

Working with Ruby shell executions by a backquote or %x syntax I found that when I declare a new variable in bash it is not visible by ruby script, until I make it environment by export command.

Please explain mechanism why do Shell Variables is not visible by a script?

# Shell and Environment variables.
V123='This is an variable. VAR HERE.'
echo $V123

# Read shell variable via Ruby
ruby -e 'p `echo $V123`' # "$V123\n"
ruby -e 'p %x[echo $V123]' # "$V123\n"

# Check SET for this var
set | grep V123
ruby -e 'p `set | grep V123`' # ""
ruby -e 'p %x[set | grep V123]' # ""

# Put this var itno the Environment
echo "--- Export"
printenv V123
export V123
printenv V123
echo "--- Ruby printenv"
ruby -e 'p `printenv V123`' # This is an variable. VAR HERE.\n"
ruby -e 'p %x[printenv V123]' # This is an variable. VAR HERE.\n" 
Mat
  • 202,337
  • 40
  • 393
  • 406
Dmitry Dmitriev
  • 929
  • 8
  • 23
  • 1
    This might help: [Difference between single and double quotes in bash](http://stackoverflow.com/q/6697753/3776858) – Cyrus May 01 '18 at 07:27
  • 3
    Why do you expect the subshell to derive the environment of the parent shell in the first place? That’s not how bash works. One might `V123=FOO ruby -e 'p \`echo $V123\`'` to explicitly pass the env var to another shell script. **Sidenote:** that behaviour has nothing to do with ruby, it’s shell subprocess default. – Aleksei Matiushkin May 01 '18 at 07:32

1 Answers1

2

This question does not really have anything to do with ruby; it's just about the behaviour of bash variables.

I found that when I declare a new variable in bash it is not visible by ruby script, until I make it environment by export command.

Sub-shells do not inherit the environment of their parent shell. You can explicitly call a sub-shell with variables, or you can export them. (That's the whole point of the export function!)

For example, consider the following - which, again, has got nothing to do with ruby.

Suppose test.txt has the following lines:

line one
line two

Observe the following outputs:

  1. When the variable is declared as a separate command, it is not passed to the sub-shell:

    GREP_OPTIONS='-v'
    grep one test.txt
    
    // Result:
    line one
    
  2. When the variable is set as part of the same command, it is passed to the sub-shell:

    GREP_OPTIONS='-v' grep one test.txt
    
    // Result:
    line two
    
  3. When the variable is exported, it is passed to the sub-shell:

    export GREP_OPTIONS='-v'
    grep one test.txt
    
    // Result:
    line two
    
Tom Lord
  • 27,404
  • 4
  • 50
  • 77