开发者

Nested conditions in Bash (if [[...)

开发者 https://www.devze.com 2023-03-04 14:34 出处:网络
I have several questions I would like to be answered since I\'m not a Bash expert so far... There are several conditions I need to check before performing a specific task, but some of them are related

I have several questions I would like to be answered since I'm not a Bash expert so far... There are several conditions I need to check before performing a specific task, but some of them are related and cannot be detached : I would like the following statement to be checked :

if ((1 OR 2) AND (3 OR 4))
   then
      blabla...
fi

I made this so far,

if [[ "[ `echo "$5" | cut -c 1-2` -lt 0 || `echo "$5" | cut -c 1-2` -gt 23 ]" && "[ `echo "$5" | cut -c 4-5` -lt 0 || `echo "$5" | cut -c 4-5` -gt 23 ]" ]]
   then
      echo "La plage horaire indiquée n'est pas valide ! Format = HH-HH"
      exit 3
fi

and it works properly. I have the feeling that there's something much easier开发者_开发技巧 that can be done in order to perform this check, but I cannot see how...

And second thing, in the code I wrote above, you can see this :

"[ `echo "$5" | cut -c 1-2` -lt 0 || `echo "$5" | cut -c 1-2` -gt 23 ]"

The simple square-bracket corresponds to the test function, right ? So why is it properly called when putting double-quotes ? I understand I could not put any backquote there, it would not make any sense with my echo "$5"... thing, but double-quotes are supposed to replace special characters such as $ and prevent from ignoring single spaces, so why is it replacing the [ character ? Is it considered as one of these special characters ?

Thank you in advance for your answers !


Don't repeat yourself:

a=$(echo "$5" | cut -c 1-2)
b=$(echo "$5" | cut -c 4-5)

or use bash parameter expansion syntax:

a=${5:0:2}
b=%{5:3:2}

And you can use arithmetic substitution:

if (( a < 0 || a > 23)) && (( b < 0 || b > 23 )); then
      echo "La plage horaire indiquée n'est pas valide ! Format = HH-HH"
      exit 3
fi


From help [[:

 ( EXPRESSION )   Returns the value of EXPRESSION
0

精彩评论

暂无评论...
验证码 换一张
取 消