Classic Bourne Shell has a handy feature that many people don’t seem to know: Parameter Expansion. Stephen Bourne describes it in An Introduction to the UNIX Shell, which is part of the original Unix V7 manuals from 1978. Among other things, parameter expansion provides a notation for making sure that variables are set and to assign default values. This is best explained by example.
Suppose you want to use a default value if a certain variable isn’t set:
echo "Hello, ${USERNAME-Unknown User}!"
This prints "Hello, Unknown User!", unless the USERNAME
variable is set. Adding a colon makes the shell use the default parameter if the USERNAME
variable contains the empty string (or is unset):
echo "Hello, ${USERNAME:-Unknown User}!"
Often, you want to assign default values right at the top of the script and be done with it. There’s an idiom that includes the rarely used null command ":":
: ${USERNAME=$LOGNAME}
The shell evaluates the arguments of the ":" command and continues. If the USERNAME
variable isn’t set, it assigns the value on the right hand side. You may want to test for the empty string, too:
: ${USERNAME:=$LOGNAME}
Sometimes it’s more useful to abort execution with an error message if a certain variable isn’t set:
: ${USERNAME?}
You can also specify an error message:
: ${USERNAME?Please set USERNAME variable}
Or test for the empty string, too:
: ${USERNAME:?Please set USERNAME variable to a non-empty value}
Bourne Shell implementations like bash(1) add many more expansion features, most notably substring processing similar to what you can do with sed(1).