Shell Variables

The term variables is used to describe all variables currently set within the shell. Running the set command will display a list of all shell variables. For a normal interactive shell, these variable/value pairs come from 3 sources:

    1. Inherited from the environment when the shell was first invoked.

    2. Set by startuo files for the shell such as /etc/profile, ~/.bash_profile, ~/.bashrc, etc

    3. Set manually by a user from the shell prompt.

Shell variables are not inherited by processes launched by a shell.The following example shows how the value of the shell variable $AGE is not visible within a new shell. It also shows the use of the unset command to destroy a variable:

[rex@ssi ~]$ AGE=42; echo $AGE 42 [rex@ssi ~]$ bash [rex@ssi ~]$ echo $AGE ---------no output------ [rex@ssi ~]$ exit exit [rex@ssi ~]$ echo $AGE 42 [rex@ssi ~]$ unset AGE; echo $AGE ---------no output-------

Environment Variables

The export command will make a shell variable an environment variable that will then be inherited by each launched process. A list of environment variables can be viewed with the env command:

[rex@ssi ~]$ AGE=42; env | grep ^AGE [rex@ssi ~]$ export AGE [rex@ssi ~]$ env | grep ^AGE AGE=42 [rex@ssi ~]$ bash [rex@ssi ~]$ echo $AGE 42

Variables can also be added to the environment inherited by a process by listing the variable/value pairs on the command line before the command. The following example shows running the crontab command but setting an environment that would cause it to launch an alternate editor running with a Russian locale:

[rex@masterdns ~]$ LANG=ru_RU EDITOR=gedit crontab -e

To launch a process and suppress the inheritance of particular environment variables, use the env -u command. The following example shows launching an SSH client process that won't see the running SSH agent process:

env -u SSH_AGENT_PID ssh bcroft@server1

Running env -i command will launch the specified command without any environment.

EOF

Shell and Environment Variables

Useful in shell scripting

Programs may malfunction if not set ($PATH, $HOME, $USER, etc)

Viewing variables

  • set (shell)

  • env (environment)

Clearing variables

  • unset (shell | environment)

  • env -u | i command (environment)