Variables#

Names#

A variable name can contain letters, digits and underscores, it just cannot start with a digit. It is a wide spread convention to use upper case letters for variable names, but this is not mandatory. It is important, to be aware of already defined environment variables to avoid name clashes.

Note

If it becomes necessary, names could be made explicit with curly braces while referencing. For example, in the expression 123${SEP}45 the variable referenced is SEP, and not SEP4 or SEP45. This is also important while using arrays.

When not declared otherwise, all variables are treated as strings. That means bash does handle A=123 as a string and not an integer. To explicitly define an integer variable use declare -i A=123 instead. This is seldom necessary as variables are casted on demand.

Types#

Most importantly, every process has its own set of variables. They are referred to as local variables or just variables. A subset of these variables are environment variables (sometimes also called global variables). The difference is how they are inherited to child processes:

  • global/environment variables/: Inherited to child processes

  • local variables: Not inherited to child processes

It important to understand, that every process has its own copy of local and environment variables. The environment is inherited from the parent process on start up. But after that, any changes to an environment variable by any other process (even the parent process) do not effect the current environment.

Some programs, most notably shells, import variables from certain files (e.g. /etc/profile, …) and add them to their environment. This interferes with variable inheritance.

Exception to Inheritance#

An important exception to rule of inheritance are sub-shells. bash might start another bash process by splitting itself up into to possesses (forking). The new split-up process is called a sub-shell. It a perfect copy of the parent process (except its pid) including the whole process state and variables. This means a sub-shell does inherit local variables from its parent.

Actually, bash executes any other program as follows: First it invokes the fork system call to split itself up (duplicating all the variables). And then the child uses an execv system call to replace itself with the program to execute (and loses all local variables).