Variables
Definition of variables
a="Hello World
Reading the content of a variable
echo $a
echo ${a}
It is the task of the shell (step 4) to expand variables.
Example:
a="Hello World"
b=$a
echo $b # we get "Hello World"
Example:
a="Hello World"
b=a
echo $b # yields a
echo $$b # yields <pid of echo>b
echo '$'$b # yields "$a"
eval echo '$'$b # Good. we get "Hello World"
Exporting Variables
Variables are defined only for the current shell
a="Hello World"
sh -c 'echo $a' # yields a empty line
export a
sh -c 'echo $a' # we get "Hello World"
Pitfalls with variables and subshells
- Variables defined in subshells are NEVER exported to the calling shell
- Pipes are executed in subshells, and in some shells while loops --> don't forget to export the variable
- bash permits to write export a=value, but this may be a syntax error in other shells
- a shellscript can be executed in the current envionment if called with source or with "."
- if a script is sourced, it must not call exit