Setting Default Values
Problem
Your script may rely on certain environment variables, either widely used ones
(e.g., $USER
) or ones specific to
your own business. If you want to build a robust shell script, you
should make sure that these variables do have a reasonable value. You
want to guarantee a reasonable default value. How?
Solution
Use the assignment operator in the shell variable reference the first time you refer to it to assign a value to the variable if it doesn’t already have one, as in:
cd ${HOME:=/tmp}
Discussion
The reference to $HOME
in the
example above will return the current value of $HOME
unless it is empty or not set at all. In
those cases (empty or not set), it will return the value /tmp
, which will also be assigned to $HOME
so that further references to $HOME
will have this new value.
We can see this in action here:
$ echo ${HOME:=/tmp} /home/uid002 $ unset HOME # generally not wise to do $ echo ${HOME:=/tmp} /tmp $ echo $HOME /tmp $ cd ; pwd /tmp $
Once we unset the variable it no longer had any value. When we
then used the := operator as part of our reference to it, the new value
(/tmp
) was substituted. The
subsequent references to $HOME
returned its new value.
One important exception to keep in mind about the assignment operator: this mechanism will not work with
positional parameter arguments (e.g., $1
or $*). For those cases, use :- in
expressions like ${1:-default}
, which
will return the value without trying to do the assignment.
As an aside, it might help you ...
Get bash Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.