Initializing variables in bash Initializing variables in bash unix unix

Initializing variables in bash


You can initialize shell variables with simple assignments

$ foo="fooval"$ echo $foo  fooval

These variables won't spread to unrelated child processes:

$ foo=fooval$ sh -c 'printf "\"%s\"" $foo'   ""

To make them spread, you need to export them into the process's (shell's)environment (make them into "environment variables" (these are commonly capitalized, i.e.,FOO instead of foo)

$ export foo$ sh -c 'echo $foo'   fooval

You can assign and export in one step:

$ export foo=fooval

Environment variables will never spread anywhere but down the process hierarchy.(Only to children, never to parents or completely unrelated processes)Therefore, if you have a script with variable assignments, you need to source it, not execute it:

 $ ./envvars #won't affect the parent shell $ . ./envvars #this will

There are no per-terminal variables (though there are per-terminal configurations with fixed keys accessible manipulatable with the stty tool).


Create a file test.sh

add the following line:

export b="key"

Now goto the terminal and do the following :

source ./test.shecho $b

Output:

key