Default shell variables value
From Linux Shell Scripting Tutorial - A Beginner's handbook
You can set the default shell variable value using the following syntax. For example, try to display the value of an undefined variable called grandslam:
echo $grandslam
Nothing will be displayed as the variable grandslam was not set in the first place. If $grandslam unset, set name to "Maria Sharapova", enter:
echo ${grandslam=Maria Sharapova}
Sample outputs:
Maria Sharapova
You can also use the following syntax:
echo ${grandslam:-DefaultValueHere}
- if $grandslam name is not set use default "Maria Sharapova":
echo ${grandslam:-Maria Sharapova}
- if $grandslam unset, set name to default "Maria Sharapova":
echo ${grandslam:=Maria Sharapova}
The := syntax
If the variable is an empty, you can assign a default value. The syntax is:
${var:=defaultValue}
Example
Type the following command at a shell prompt:
echo ${arg:=Foo} bank=HSBC echo ${bank:=Citi} unset bank echo ${bank:=Citi}
In this example, the function die assigns a default value if $1 argument is missing:
die(){ local error=${1:=Undefined error} echo "$0: $LINE $error" } die "File not found" die
The second die call will produce an error on screen:
bash: $1: cannot assign in this way
Update the die function as follows:
die(){ local error=${1:-Undefined error} echo "$0: $LINE $error" } # call die() with an argument die "File not found" # call die() without an argument die