Home > Enterprise >  How to use a while loop to check if a variable is empty or not
How to use a while loop to check if a variable is empty or not

Time:12-29

I am using following code to check whether variable is empty or not. I'm using while loop because I need to continue the loop until the variable is empty. The moment the variable is set to a value the loop should exit.

MR=[]
while [ -z "$MR" ]
do 
    echo "in while loop"
    sleep 10s
    MR="hi"
done 

For some reason, it is not at all executing. What is the reason?

CodePudding user response:

What is the reason?

MR variable is not empty, it contains two characters [ and ].

$ MR=[]
$ echo "$MR"
[]

Because it is not empty, [ -z "$MR" ] returns nonzero, so while is never executed.

Instead set the variable to en empty string.

MR=
# or, does the same, but for some is more readable:
MR=""
# or
MR=''
  • Related