【问题标题】:Using variables in loop bash在循环 bash 中使用变量
【发布时间】:2020-10-20 12:55:28
【问题描述】:

我有四个变量,例如:

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

【问题讨论】:

  • 有数字零(0),有空变量(""),有未设置的变量。但是null 应该是什么?
  • 谢谢,请检查更新
  • 可以将这些作为"11 22 111 222" 形式的变量传递吗?
  • 没有这些是分开的

标签: bash loops variables eval


【解决方案1】:

使用变量间接扩展:

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

但是这种方式不起作用,它会检查:

因为您从未扩展变量,所以您的代码中的 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

但不需要邪恶的评估。

【讨论】:

    猜你喜欢
    • 2017-06-15
    • 1970-01-01
    • 2019-02-21
    • 1970-01-01
    • 2022-01-04
    • 2014-01-07
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    相关资源
    最近更新 更多