【问题标题】:Bash - Check which variable is not equal to zeroBash - 检查哪个变量不等于零
【发布时间】:2020-10-28 19:05:00
【问题描述】:

我正在尝试编写一个多条件检查 if 语句,并且我正在寻找一种优化的方式,而不是传统的方式。

假设有三个变量 (x, y & z) 的值在一段时间内不断变化,并且是从一些唯一的文件中获取的,如果这些变量中的任何一个值变为零,那么我们将该变量替换为来自其他预定义变量即 (a, b & c)。

如果您查看第一个 elif 条件,您会发现我必须编写两个级别的 if elif。我想避免这么多行代码。这里有任何建议。

a=1
b=2
c=3
x=`cat test.txt | grep 'assigned_value' | awk -F':' '{print$2}'`
y=`cat test1.txt | grep 'assigned_value' | awk -F':' '{print$2}'`
z=`cat test2.txt | grep 'assigned_value' | awk -F':' '{print$2}'`

if [[ $x -eq 0 && $y -eq 0 && $z -eq 0 ]]; then
    # execute something like below
    x=a
    y=b
    z=c
elif [[ $x -ne 0 ]]; then
    # check if y & z are equal to zero
    if [[ $y -eq 0 ]]; then
        # replace y with 'b' value
        y=b
        if [[ $z -eq 0 ]]; then
        # replace z with 'c' value
        z=c
        elif [[ $z -ne 0 ]]; then
        # that mean's variable x and z are already having some value and hence change is done only in variable y
        fi
    elif [[ $y -ne 0 ]]; then
        #check if z is equal to zero and replace its value
        if [[ $z -eq 0 ]]; then
        # replace z with 'c' value
        z=c
        elif [[ $z -ne 0 ]]; then
        # that mean's variable x and y are already having some value and hence change is done only in variable z
        fi
    fi
elif [[ similar check for variable y ]]; then
elif [[ similar check for variable z ]]; then
elif [[ $x -ne 0 && $y -ne 0 && $z -ne 0 ]]; then
    # do nothing as x, y & z already have some values associated
fi```

【问题讨论】:

    标签: bash if-statement scripting


    【解决方案1】:

    变量 x、y 和 z 的计算不相互依赖,因此您可以分别处理每个变量:

    a=1
    b=2
    c=3
    
    x=$(cat test.txt  | grep 'assigned_value' | awk -F':' '{print$2}')
    y=$(cat test1.txt | grep 'assigned_value' | awk -F':' '{print$2}')
    z=$(cat test2.txt | grep 'assigned_value' | awk -F':' '{print$2}')
    
    if [[ $x -eq 0 ]] ; then
        x="$a"
    fi
    
    if [[ $y -eq 0 ]] ; then
        y="$b"
    fi
    
    if [[ $z -eq 0 ]] ; then
        z="$c"
    fi
    

    【讨论】:

      【解决方案2】:

      您描述的逻辑是“如果这些变量中的任何一个值变为零,那么我们用其他预定义变量(即 (a, b & c))中的值替换该变量”。

      这可以翻译成简单的 bash 语句:

      (( $x )) || x="$a"
      (( $y )) || y="$b"
      (( $z )) || z="$c"
      

      编辑:说明:
      在布尔上下文中,数字 0 被视为 false 而不等于 0 的数字被视为 true
      || 是一个逻辑或(通常用于实现故障转移)运算符。逻辑的右侧或仅在左侧解析为 false 时才执行。
      因此,您可以将第一行解释为“检查 $x 是否为数字!= 0,如果不是,则将 $a 分配给它

      【讨论】:

      • 你能解释一下这里发生了什么吗?在第一个参数中检查我们到底在检查什么?
      猜你喜欢
      • 2012-10-16
      • 1970-01-01
      • 1970-01-01
      • 2014-11-10
      • 2019-11-17
      • 2015-05-20
      • 2018-01-18
      • 2015-08-07
      相关资源
      最近更新 更多