Setting defaults

Using either the test command or the brackets, we can provide default values for variables, including command-line parameters. Taking the hello4.sh script we worked with earlier, we can modify it and set the name parameter if it is zero bytes:

#!/bin/bash
name=$1
[ -z $name ] && name="Anonymous"
echo "Hello $name"
exit 0

This code is functional but it is our choice how we code in the default value. We can, alternatively, assign a default value directly to the parameter. Consider the following command, where a default assignment is made directly:

name=${1-"Anonymous"}

In bash, this is known as parameter substitution and can be written in the following pseudo-code:

${parameter-default}

Wherever a variable (parameter) has not been declared and has a null value, the default value will be used. If the parameter has been explicitly declared with a null value, we will use the :- syntax, as shown in the following example:

parameter=
${parameter:-default}

By editing the script now, we can create hello8.sh to make use of bash parameter substitution to provide the default value:

#!/bin/bash
#Use parameter substitution to provide default value
name=${1-"Anonymous"}
echo "Hello $name"
exit 0

This script and its output, both with and without a supplied value, are shown in the following screenshot:

The hello8.sh script provides the functionality that we need, with the logic built directly into the parameter assignment. The logic and assignment are now a single line of code within the script and this is a major step in keeping the script simple and maintaining the readability.