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?
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}
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 to remember some of these crazy
symbols if you think of the visual difference between ${VAR:=value}
and ${VAR:-value}
. The := will do an assignment as
well as return the value on the right of the operator. The :- will do
half of that—it just returns the value but doesn’t do the assignment—so
its symbol is only half of an equal sign (i.e., one horizontal bar, not
two). If this doesn’t help, forget that we mentioned it.
3.149.27.72