具有多个条件的 Bash if 语句会引发错误 [英] Bash if statement with multiple conditions throws an error
本文介绍了具有多个条件的 Bash if 语句会引发错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个脚本来检查两个错误标志,如果一个标志(或两个)被更改,它会回显——错误发生了.我的脚本:
I'm trying to write a script that will check two error flags, and in case one flag (or both) are changed it'll echo-- error happened. My script:
my_error_flag=0
my_error_flag_o=0
do something.....
if [[ "$my_error_flag"=="1" || "$my_error_flag_o"=="2" ] || [ "$my_error_flag"="1" && "$my_error_flag_o"="2" ]]; then
echo "$my_error_flag"
else
echo "no flag"
fi
基本上,应该是这样:
if ((a=1 or b=2) or (a=1 and b=2))
then
display error
else
no error
fi
我得到的错误是:
line 26: conditional binary operator expected
line 26: syntax error near `]'
line 26: `if [[ "$my_error_flag"=="1" || "$my_error_flag_o"=="2" ] || [ "$my_error_flag"="1" && "$my_error_flag_o"="2" ]]; then'
我的括号弄乱了吗?
推荐答案
使用 -a
(for and) 和 -o
(for or) 操作.
Use -a
(for and) and -o
(for or) operations.
tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html一个>
更新
实际上,您仍然可以将 &&
和 ||
与 -eq
操作一起使用.所以你的脚本应该是这样的:
Actually you could still use &&
and ||
with the -eq
operation. So your script would be like this:
my_error_flag=1
my_error_flag_o=1
if [ $my_error_flag -eq 1 ] || [ $my_error_flag_o -eq 2 ] || ([ $my_error_flag -eq 1 ] && [ $my_error_flag_o -eq 2 ]); then
echo "$my_error_flag"
else
echo "no flag"
fi
尽管在您的情况下,您可以丢弃最后两个表达式,而只使用一个或这样的操作:
Although in your case you can discard the last two expressions and just stick with one or operation like this:
my_error_flag=1
my_error_flag_o=1
if [ $my_error_flag -eq 1 ] || [ $my_error_flag_o -eq 2 ]; then
echo "$my_error_flag"
else
echo "no flag"
fi
这篇关于具有多个条件的 Bash if 语句会引发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文