Use := to Assign a Default Value to an Unset Variable

You can change the value of a null or unset variable to its default in a script using the := modifier:


${name:=default}

When the shell expands the expression ${name:=default}, it sets the value of name to the expanded value of default. If a script contains a line such as the following and LIT is unset or null at the time this line is executed, the shell assigns LIT the value /home/max/literature:


$ ls ${LIT:=/home/max/literature}

Shell scripts frequently start with the : (null) builtin followed on the same line by the := expansion modifier to set any variables that might be null or unset. The : builtin evaluates each token in the remainder of the command line but does not execute any commands.

Use the following syntax to set a default for a null or unset variable in a shell script (a SPACE follows the first colon). Without the leading colon (:), the shell would evaluate and attempt to execute the “command” that results from the evaluation.


: ${name:=default}

When a script needs a directory for temporary files and uses the value of TEMPDIR for the name of this directory, the following line assigns to TEMPDIR the value /tmp if TEMPDIR is null:


: ${TEMPDIR:=/tmp}
 •  0 comments  •  flag
Share on Twitter
Published on May 03, 2012 15:20
No comments have been added yet.


Mark G. Sobell's Blog

Mark G. Sobell
Mark G. Sobell isn't a Goodreads Author (yet), but they do have a blog, so here are some recent posts imported from their feed.
Follow Mark G. Sobell's blog with rss.