There are multiple ways to check if a variable is empty and then set it to some default value. Shell parameter expansion gives us an elegant way to do this in one line. Here are sample code snippet for this.
Using default value if empty
We’ll use ${VAR:-}
#!/bin/bash ## x not initialised ## v will have value Hello. x does not change v=${x:-"Hello"} echo "v=$v" ## x set to empty string x="" v=${x:-"Hello2"} echo "v=$v" ## x set to space (not empty string) x=" " v=${x:-"Hello3"} echo "v=$v"
v=Hello v=Hello2 v=
Env: GNU bash, version 4.2.46
Assigning to default value if empty
We’ll use ${VAR:=}
#!/bin/bash ## v not initialised somevar=${v:="Hello"} echo "v=$v" ## v set to empty string v="" somevar=${v:="Hello2"} echo "v=$v" ## v set to space (not empty string) v=" " somevar=${v:="Hello3"} echo "v=$v"
v=Hello v=Hello2 v=
Env: GNU bash, version 4.2.46
Few points to note
- Only unassigned variable and empty string will be considered empty for taking/setting default value.
- space or newlines or 0 are not considered empty for taking/setting default value.
-
Instead of
:=
and:-
we can also use=
and-