BASH – Determining that a variable is empty

Hi everyone

Today I had to script a bit inside a Linux VM on Azure. I had to make some test inside a bash script. To my extent I’am not a Linux expert, but I wanted to share a small tip I found.

How to find is a variable is empty or unset in BASH ?

To find if a variable is SET to empty to a “” string please use the comand :

if [ -z “$VAR” ];

Another way to write it would be with double bracket :

if [[ -z $var ]]
if [[ -z “$var” ]]
if [[ ! $var ]]
if [[ ! “$var” ]]

or that expression would check if it’s with a value :

if [[ $var ]]

 

Thanks everyone, enjoy the small tip

Advertisement