Bash - 检查哪个变量不等于零

标签 bash if-statement scripting

我正在尝试编写一个多条件检查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```

最佳答案

变量 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

关于Bash - 检查哪个变量不等于零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62793626/

相关文章:

javascript - 使用命名函数设置多个事件响应

arrays - 在 AWK 中使用 Bash 数组

linux - 如何通过 `bash`判断一个线程是不是内核线程?

c++ - C/C++中不带括号的else语句的多行格式

powershell - PowerShell 中 If 语句的多变量条件

scripting - 如何分割字符串并在ant脚本的for循环中使用它?

linux - 根据条件将 bash 中的 CSV 文件拆分为多个文件

bash - 可能的攻击 : echo -e

java - 检查类型是否为接口(interface)

linux - 在 for 循环中从数组创建目录