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

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

When you run your shell script, it executes in a new shell instance, and does not inherit any variables instantiated in the interactive shell instance.

Specific variables can be inherited this way, called environment variables. You make a variable assignment an environment variable by using export, such as export foo=bar. This is the bash syntax, other shells may use env or some other method.

You can also cause the shell script to execute in the same shell instance by 'sourcing' it. You can do this with . (note the period) or using source You can do this in your interactive session, or you can do this from within a shell script. This is really handy for creating shell "libraries", where you source in a set of shell functions or variable definitions from an external file. Super handy.

For instance:

. /path/
echo $foo # foo is instantiated in
do_something # this is a shell function from

where is:

do_something() {
echo "I am do_something"

Another option could be to pass the variable to your script as an argument.

./ $foo

The issue then becomes the contents of ./

It would have to echo $1 instead of echo $foo - the $1 indicating the first argument passed to the script.