【发布时间】: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