Bash Environment Variables – What Are the Default Environment Variables

bashenvironment-variables

When starting a bash shell process, what are the default environment variables, except those specified in the startup file?

Is it correct that some bash or sh builtin variables (listed in the "Bourne Shell Variables" and "Bash Variables" sections of the Bash manual) are default environment variables while other bash or sh builtin variables are not? What kinds of bash or sh builtin variables are default environment variables?

In the POSIX definition of environment variables it seems that all or most of the builtin variables in bash are environment variables by default, but I am not sure.

Best Answer

A process normally inherits envrionment variables from its parent process. Unless programs (e.g. shells) have other conventions, there is no "default" environment variable.

If you are curious, you could use the env -i command to clear the environment and use printenv to show the environment. Some examples:

$ env -i printenv

$ env -i sh -c printenv
PWD=/home/peter
SHLVL=1
_=/usr/bin/printenv

$ echo printenv | env -i sh
PWD=/home/peter
SHLVL=1
_=/usr/bin/printenv

$ env -i sh --login -c printenv
...all kinds of variables from login scripts...
LANG=en_US.UTF-8
PWD=/home/peter
SHLVL=1
PATH=/usr/local/bin:/usr/bin:...
LESSOPEN=|/usr/bin/lesspipe.sh %s
_=/usr/bin/env

The bash(1) manual documents some of these variables, but unfortunately it does not provide a definitive answer on whether these environment variables are always set or not.

Other variables in bash can be found in a similar way:

$ env -i -c set
BASH=/usr/bin/sh
...
BASH_VERSION='4.4.5(1)-release'
...
SHLVL=1
TERM=dumb
UID=1000
_=sh

If you need to rely on any of these variables, it is best to check the bash manual. In particular:


Now given that you have an open bash shell. You would like to know if a certain variable is available to subshells or not. For this, the declare -p NAME... builtin can be used to "display the attributes and value of each NAME. Example:

$ declare -p PWD
declare -x PWD="/home/peter"
$ declare -p foo
bash: declare: foo: not found
$ foo=bar
$ declare -p foo
declare -- foo="bar"

The -x attribute mark a variable as exported which means that subprocesses see this variable. To do this for existing variables, you can use the export builtin:

$ export foo
$ declare -p foo
declare -x foo="bar"

In Bash, setting a variable and making it available to subprocesses can be combined:

$ export foo=bar
Related Question