Bash – set default value if a variable is empty

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.
bash-variable-default-value-shell-parameter-expansion

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.3.11

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.3.11

Few points to note

  1. Only unassigned variable and empty string will be considered empty for taking/setting default value.
  2. space or newlines or 0 are not considered empty for taking/setting default value.
  3. Instead of := and :- we can also use = and -
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments