在循环 bash 中使用变量

Using variables in loop bash

我有四个变量,例如:

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

现在我想创建一个循环来检查它是否为空:

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

我想数 variable a and b 然后打印它的内容。但这种方式行不通,它会检查:

a1
a2
b1
b2

但我需要检查:

11
22
111
222

使用变量间接扩展:

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:

因为您从未展开变量,所以您的代码中 eval 没有任何意义。您的代码只是:

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

虽然你可以:

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

但不需要恶意评估。