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