16. Environments

After all expansions of the user input are done and quote removal has succeeded. Bash performs commands and executes them. Built-in commands like read, for or exit are executed all within the current Bash process. External commands, like find or commands running in a pipe as well as subshells are executed in a own child processes of the shell. Each child process has it's own execution environment derived from it's parent shell.

Program sequence: Built-ins are run in the shell process, all others in a separate child process.
Figure 2: Program sequence: Built-ins are run in the shell process, all others in a separate child process.

An environment is basically a set of variables and functions which are marked for copying into a child process. A mark can be set by the declare command:

$ declare -x verse="Oranges and lemons say the bells of St. Clement's"

or by using the export command:

$ export film="A Clockwork Orange"

Functions can be marked by applying the -f option to their name to the export command:

$ function parameters() {
  echo $@
}
$ export -f parameters

The environment can be listed by the env command:

$ env
!::=::\
_=/usr/bin/env
film=A Clockwork Orange
verse=Oranges and lemons say the bells of St. Clement's
parameters=() {  echo $@
}

The execution environment of a shell consists of all files opened by the shell, variables and functions both derived from it's parent environment or set after its creation, traps being set, options being set, aliases, various process ids, the file mask mode and the current working directory both derived from it's parent environment or set after its creation.

Commands running in a pipe, started asynchronous or orginating by command substitution, are run in a subshell. The subshell is invoked within a copy of the current execution environment, except traps. They are reset. A subshell can be formed by enclosing commands within round brackets also:

$ (exit 1)

The exit command is a Bash built-in. Without the brackets, it would close the terminal, because built-in commands are executed in the same process as the shell. Within brackets, exit terminates the process of the subshell.

External commands are invoked in a separate execution environment that includes the actual create mask and working directory, opened files, variables and functions being exported. Traps are reset to the values the shell inherited from its parent.