Bash-检查哪个变量不等于零
我正在尝试编写一个多条件检查if语句,我正在寻找一种优化的方法,而不是传统的方法 假设有三个变量(x、y和z)的值在一段时间内不断变化,并且是从一些唯一的文件中获取的,如果这些变量中的任何一个值变为零,那么我们将用其他预定义变量(a、b和c)的值替换该变量 如果您查看第一个elif条件,您可以看到我必须编写两个级别的if elif。我想避免太多的代码行。这里有什么建议吗Bash-检查哪个变量不等于零,bash,if-statement,scripting,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':'
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
变量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
您描述的逻辑是“如果这些变量中的任何一个值变为零,那么我们将用其他预定义变量(a、b和c)的值替换该变量”。
这可以转换为简单的bash语句:
(( $x )) || x="$a"
(( $y )) || y="$b"
(( $z )) || z="$c"
编辑:说明:在布尔上下文中,数字0被视为false,而不等于0的数字被视为true。
|
是逻辑or(通常用于实现故障切换)运算符。只有当左侧解析为false时,才会执行逻辑or右侧的内容。因此,您可以将第1行解释为“检查$x是否为数字!=0,如果不是,则将$a分配给它”您描述的逻辑是“如果这些变量中的任何一个值变为零,则我们将该变量替换为其他预定义变量的值,即(a、b和c)。
这可以转换为简单的bash语句:
(( $x )) || x="$a"
(( $y )) || y="$b"
(( $z )) || z="$c"
编辑:说明:在布尔上下文中,数字0被视为false,而不等于0的数字被视为true。
|
是逻辑or(通常用于实现故障切换)运算符。只有当左侧解析为false时,才会执行逻辑or右侧的内容。因此,您可以将第1行解释为“检查$x是否为数字!=0,如果不是,则将$a分配给它”您能解释一下这里发生了什么吗?在第一个参数检查中,我们到底在检查什么?你能解释一下这里发生了什么吗?在第一个参数检查中,我们到底在检查什么?