【问题标题】:Is there a way to assign bool variable in bash?有没有办法在 bash 中分配 bool 变量?
【发布时间】:2020-05-20 21:30:17
【问题描述】:

我的要求如下,

if cond1 is true; then
    if [[ val1 -lt val2 ]]; then
        call_x_func
        call_y_func
        call_z_func
    fi
else
    if [[ val1 != val2 ]]; then
        call_x_func
        call_y_func
        call_z_func
    fi
fi

从上面可以看出,如果 cond1 为真,则使用 operator -lt 或使用 !=。循环内的内容保持不变。为了实现这一点,我试图在下面做,但无法将 bool 值分配给 bash 变量。最好的方法是什么?

need_change=false
if cond1; then
    need_change=[[ val1 -lt val2 ]]
else
    need_change=[[ val1 != val2 ]] 
fi

if $need_change; then
    call_x_func
    call_y_func
    call_z_func
fi

【问题讨论】:

  • bash 中的 false 表示未设置。您可以使用 ((need_change)) 来检查它是否为真(或设置)
  • 小于和不等于总是会给你错误的,是吗?至少在 bash 中
  • 另外,无论测试结果如何,您都在调用相同顺序的函数...
  • 您不能将[[ ... ]] 分配给参数;这是一个命令,而不是一个值。

标签: bash variables boolean boolean-logic


【解决方案1】:

我经常使用“true”和“false”,因为它们也是分别仅返回成功和失败的命令。然后就可以了

cond1=false
if "$cond1"; then ...fi

这里是你要找的东西:

need_change=false
cond1=true
if "$cond1"; then
    if [[ val1 -lt val2 ]]; then need_change="true"; else need_change="false"; fi
else
    if [[ val1 -ne val2 ]]; then need_change="true"; else need_change="false"; fi
fi

if "$need_change"; then
    .
    .
fi

【讨论】:

  • @Jetchisel 嗯,他可以用标志变量模拟 if/then/else 逻辑
  • @Jetchisel 兄弟现在有意义吗?
  • A && B || C 不是“总是错的”。人们只需要知道如果 B 退出非零会发生什么。变量赋值(不使用命令替换)将退出状态为零。 [[ condition ]] && var=foo || var=bar 很好。
  • 是的,我可能用错了词,但要习惯&& ||,因为在这个特殊情况下它可以工作会让脚本编写者养成一个坏习惯,因为与使用 if 语句相比,总有一个问题,并且这个论坛有成千上万的人在寻找特定的解决方案,并且大多数时候这里的代码最终都用于生产。
【解决方案2】:

由于 bash 没有 bool 数据类型,我建议您通过将数值 0 解释为 true 并将任何其他值解释为 false 来对 bool 进行建模。通过这样做,您可以轻松地将程序的退出代码用作布尔值。例如:

need_change=1  # set to false
((val1 < val2)) # Test the values
need_change=$? # Set to true or false, according to the outcome of the test
  # or:
need_change=$((val1 < val2)) # Alternative way to achieve this result.

【讨论】:

    猜你喜欢
    • 2013-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 2017-10-10
    • 2022-01-14
    • 2013-07-01
    • 2014-02-11
    相关资源
    最近更新 更多