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" 
2
  • 1
    This might help: Difference between single and double quotes in bash Commented May 1, 2018 at 7: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. Commented May 1, 2018 at 7:32

1 Answer 1

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
    
Sign up to request clarification or add additional context in comments.

Comments

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.