多个条件如果声明bash脚本 [英] Multiple Conditions If Statement Bash Script

查看:113
本文介绍了多个条件如果声明bash脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个脚本,将检查两个错误标志,并在情况下,一个标志(或两者)都改变了,它会echo--发生错误。我的脚本:

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

基本上,它应该是,沿东西:

Basically, it should be, something along:

if ((a=1 or b=2) or (a=1 and b=2))
  then
     display error
else
     no error
fi

我得到的错误是:

The error I get is:

 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'

是我的括号搞砸了?

Are my brackets messed up?

推荐答案

使用 -a (并)和 -o (用于或)操作。

Use -a (for and) and -o (for or) operations.

<一个href=\"http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html\">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

虽然你的情况,你可以放弃的最后两个前pressions,只是坚持使用一个或操作是这样的:

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脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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