1

I have four variables like:

a1="11"
a2="22"
b1="111"
b2="222"

and now I want to create a loop to check if it is null or not:

for (( i=1; i<=2; i++)); do
    eval "a=a$i"
    eval "b=b$i"
    if [ -z $a ] || [ -z $b ]; then
        echo "variable-$a: condition is true"
    fi
done

I want to count variable a and b then print the content of that. But in this way doesn't work and it checks:

a1
a2
b1
b2

But I need to check:

11
22
111
222
4
  • 1
    There is the number zero (0), there are empty variables (""), there are unset variables. But what is null supposed to be? Commented Jun 30, 2020 at 9:05
  • Thank you, please check the update Commented Jun 30, 2020 at 9:06
  • Could these be passed as one variable of the form "11 22 111 222" instead? Commented Jun 30, 2020 at 9:08
  • No these are seperated Commented Jun 30, 2020 at 9:09

1 Answer 1

1

Use variable indirection expansion:

for (( i=1; i<=2; i++)); do
    a=a$i
    b=b$i
    if [ -z "${!a}" ] || [ -z "${!b}" ]; then
        echo "variable-$a: condition is true"
    fi
done

But in this way doesn't work and it checks:

Because you never expanded the variables, there is no point in eval in your code. Your code is just:

for (( i=1; i<=2; i++)); do
    a="a$i"
    b="b$i"
    # Remember to quote variable expansions!
    if [ -z "$a" ] || [ -z "$b" ]; then
        echo "variable-$a: condition is true"
    fi
done

while you could:

for (( i=1; i<=2; i++)); do
    eval "a=\"\$a$i\""
    eval "b=\"\$b$i\""
    if [ -z "$a" ] || [ -z "$b" ]; then
        echo "variable-a$i: condition is true"
    fi
done

but there is no need for evil eval.

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.