Bash – how to check if a variable is set

To check if a variable is set or empty, we can use couple of approaches. One approach is to use empty string check (if [ -z $string]) . This approach is little inaccurate but will work in most cases. Better approach is to use parameter substitution (${var+val}) and then empty string check (if [ -z $string]).

Parameter substitution using ${var+val}

If variable var is set then use val otherwise null.

#!/bin/bash
var=somethings
echo ${var+val}
val
Env: GNU bash, version 4.3.11

Bash code – check if a variable is set

Here empty string will be considered as set.

#!/bin/bash
if [ -z ${var+x} ]; then
  echo "variable var is not set"
else
  echo "variable var is set"
fi

var=""
if [ -z ${var+x} ]; then
  echo "variable var is not set"
else
  echo "variable var is set"
fi
variable var is not set
variable var is set
Env: GNU bash, version 4.3.11
Note that in ${var+x} we can use any string in place of x.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments