Shell variables

Shell variables are created when assigned. The assignment statement has strict syntax. There must be no spaces around the = sign and assigned value must be a single word, which means it must be quoted if necessary. the value of a shell variable is extracted by placing a $ sign in front of it. For example,

side=left

creates a shell variable side with the value left.

Some shell variables are predefined when you log in. Among these are the PATH, which we have discussed in Section 5.1.3. The variable HOME contains the full path name of your home directory, the variable USER contains your user name.

Variables defined in the shell can be made available to shell scripts and programs by exporting them to be environment variables. For example,

export HOME=/home/alice

defines the value of HOME variable and exports it to all scripts and programs that we may run after this assignment. Try the following script:

#!/bin/sh
#test.sh
echo "HOME="$HOME
echo "USER="$USER
echo "my pathname is " $0
prog=$(basename $0)
echo "my filename is " $prog

Note that $0 gives the pathname of the script as it was invoked. If we are interested in the filename of the script, then we need to strip the leading directories in the name. The commandbasename does that for us nicely. Also by using $(basename), we can take the output frombasename and store it in our variable.

Other useful pre-defined shell variables. The variable $$ gives the process-id of the shell script. The value $? gives the return value of the last command. The value$! gives the process id of the last command started in the background with &.