Bourne Shell Parameter Expansion

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).

This entry was posted in shell and tagged , . Bookmark the permalink.

3 Responses to Bourne Shell Parameter Expansion

  1. Danilo Piazzalunga says:

    I used to think that parameter expansion was introduced by Bash or POSIX sh, then I found this tutorial (written in the early 90’s): http://www.grymoire.com/Unix/Sh.html

  2. mike says:

    Thank you for this excellent and clear explanation!

  3. Settel says:

    Coding in Sh/Bash for well over 10 years now and still get to learn new stuff. Neat trick to combine “:” with the assignment expansion to create a one-liner that sets a default value.

Leave a Reply to Danilo Piazzalunga Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s