具有多个条件的Bash if语句会引发错误 [英] Bash if statement with multiple conditions throws an error

查看:515
本文介绍了具有多个条件的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 (对于和)和 -o (对于或者)操作。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆