3

I am using following code to check whether variable is empty or not.

I'm using a while loop because I need to continue the loop while 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?

5
  • [] is not an empty array. It's a literal string [], which is not the empty string. Commented Dec 28, 2021 at 19:22
  • An empty array would be MR=() (ignoring the fact that MR=() doesn't actually define a variable; it only sets the array attribute on the name MR). Commented Dec 28, 2021 at 19:23
  • ok. got it. so can you suggest how to write while loop if any specific command is returning literal string or not . and continue the loop unless the variable is not empty literal string Commented Dec 28, 2021 at 19:30
  • @chepner What's the difference between defining a variable and setting the array attribute? I'm not familiar with the distinction. Commented Dec 28, 2021 at 19:31
  • MR=() is basically equivalent to declare -a MR. MR will still test as undefined with [[ -v MR ]], for example, but declare -p MR will show it as declare -a MR=(). Commented Dec 28, 2021 at 20:06

1 Answer 1

5

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=''
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.