Shell – Setting variables from shell: how to use them in a script

shell-scriptvariable

How can I set variables to be used in scripts as well? They don't have to be global / system-wide, just the current session is sufficient. But for some reason they seem gone even if I run a script right from my current terminal.

Example:

foo=bar
echo "$foo"

output: bar

However if test.sh contains echo "$foo" and I do:

foo=bar
./test.sh

The output is empty. How do I set a scope for temporary variables with a terminal session that remains valid when executing scripts from that same session?

Best Answer

export foo=bar will set the global variable $foo to bar. You can also use foo=bar ./test.sh as a single command to set foo to bar for test.sh.

Related Question