Bash: Using or setting a default value for null or unset variables

If a variable is not set or if its value is null, the default behavior of Bash is to expand it to a null string. Bash provides three alternatives to this default behavior.

  1. Use a default value instead of the null string.
  2. Set a default value for the variable and use that value.
  3. Display an error message and exit the script with an exit code of 1.

To make use of these features you need to use the full syntax for accessing variables: ${variable_name}. The shorthand $variable_name does not work.

An unset variable is a variable that is not yet created or has been unset explicitly.

Use a default value

The syntax for using a default value is ${variable_name:-default_value}. If the variable is not set or null the default value is used, else the value of the variable is used. The variable is not set to the default value.

echo ${VAR:-Hello world}

Set and use a default value

To set and use a default value for null or unset variables, use the following syntax ${variable_name:=default_value}. Here we use := instead of :-. If the variable is null or unset, it is set to the default value. Then the variable is expanded as usual.

echo ${VAR:=Hello world}

Sometimes you just want to set a default value for null or unset variables but do not want to execute any command. You cannot just pass the variable and its default value to Bash like so:

av@ubuntu:~$ ${VAR:=Hello world}
bash: Hello: command not found

Bash will expand the expression and try to execute it. This could get worse if the variable contains some actual Bash command. The Bash null command can be used to get around this problem. The null command is represented by a colon (:), it is a command that does nothing. You can supply arguments to the null command, in which case, the arguments are evaluated but nothing is executed.

: ${VAR:=Hello world}

This will set the default value if required, while not trying to execute the value of the expression.

Display an error message and exit the script

In some cases, you may want to exit a script if a variable is not set or is null. The (:?) option allows you to exit the script with an error message. The error message is sent to standard error and the exit code of the script is set to 1. The syntax is : ${variable_name:?error_message}.

cd ${VAR:?error}

In the interactive shell, the (:?) will not cause an exit, the error message will be displayed.

Leave a Comment

Your email address will not be published.