How to Check If a Bash Variable is Null or not

This post will guide you how to find out if a bash variable is null or not in your Linux system.

check if a bash variable is null or not1

You just need to use the If or test commands with the -z option to check if a bash variable is null or not.

For example, you want to check a bash variable “osetc” is set or unset in your current bash shell prompt, and you just need to run one of the following bash shell command:

$ if [ -z "$osetc" ]; then echo "this variable is null"; else echo "this variable is not null"; fi

Or

$  [ -z "$osetc" ] && echo "this variable is null" || echo "this variable is not null"

Or

$ [[ ! -z "$var" ]] && echo "this variable is not null" || echo "this variable is null"

Outputs:

devops@devops:~$ if [ -z "$osetc" ]; then echo "this variable is null"; else echo "this variable is not null"; fi
this variable is null

devops@devops:~$ [ -z "$osetc" ] && echo "this variable is null" ||echo "this variable is not null"
this variable is null

devops@devops:~$ [[ ! -z "$osetc" ]] && echo "this variable is not null" || echo "this variable is null"
this variable is null

Let’s set the variable “osetc” in your current bash shell, and then check if with one of the above command:

$ osetc="test"

Outputs:

devops@devops:~$ osetc="test"

devops@devops:~$ if [ -z "$osetc" ]; then echo "this variable is null"; else echo "this variable is not null"; fi
this variable is not null

devops@devops:~$ [[ ! -z "$osetc" ]] && echo "this variable is not null" || echo "this variable is null"
this variable is not null

devops@devops:~$ [ -z "$osetc" ] && echo "this variable is null" || echo "this variable is not null"
this variable is not null

 

You might also like:

Sidebar



back to top