Cover V02, I06
Article
Listing 1
Sidebar 1
Sidebar 2
Table 1
Table 2
Table 3

nov93.tar


Sidebar: Shell Variable Substitution

You can test and change the shell variables in a variety of ways without using the shell's if command or the test(1) command. I show only the Bourne Shell's methods here, because it is the shell used most portably for programming. However, the csh and ksh's substitution abilities are richer than sh's abilities. If you're programming with either of the other shells, spend time investigating their substitution features. They're worth it. sh surrounds the variable name with braces, putting the $ outside of the braces, when referring to a variable substitution operation.

${var} -- Use this format when embedding the value of a variable inside another value, such as a prefix or suffix. If the other value won't confuse the shell about the name of the variable, you don't need the braces. For example, given

things=more
want=${things}stuff

the variable $want gets the value morestuff. Without the braces, the shell might think the variable name is $thingsstuff. However, in the directory setting,

newdir=$MAINDIR/new

the braces aren't needed because the slash is a sufficient separator.

${var:-value} -- If the variable exists in the environment and has a value, yield its value. Otherwise, use the value named after the :- characters. This is the simplest form of substitution, yielding up the named value only if the variable doesn't already have one.

${var:=value} -- If the variable exists in the environment and has a value, yield its value. Otherwise, assign the value named after the := characters to the variable and yield the new value.

${var:?value} -- If the variable exists in the environment and has a value, yield its value and do nothing else. Otherwise, print the value named after the :? characters and exit the shell.

${var:+value} -- If the variable exists in the environment and has a value replace it with the value named after the :+ characters. Leave the variable alone otherwise.