Search code examples
bashloopsvariableseval

Using variables in loop bash


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

Solution

  • 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.