Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do complex conditionals in bash? (mix of 'and' &&, 'or' || ...)

Tags:

How do I accomplish something like the following in Bash?

if ("$a" == "something" || ($n == 2 && "$b" == "something_else")); then   ... fi 
like image 207
Suan Avatar asked Apr 23 '12 22:04

Suan


People also ask

How do you use && in bash?

"&&" is used to chain commands together, such that the next command is run if and only if the preceding command exited without errors (or, more accurately, exits with a return code of 0). "-" is a command line argument with no specific bash function.

What is the and operator in bash?

Bash AND Logical Operator Bash boolean AND operator takes two operands and returns true if both the operands are true, else it returns false.

How do you use multiple IF statements in shell script?

To use multiple conditions in one if-else block, then elif keyword is used in shell. If expression1 is true then it executes statement 1 and 2, and this process continues. If none of the condition is true then it processes else part.


1 Answers

You almost got it:

if [[ "$a" == "something" || ($n == 2 && "$b" == "something_else") ]]; then 

In fact, the parentheses can be left out because of operator precedence, so it might also be written as

if [[ "$a" == "something" || $n == 2 && "$b" == "something_else" ]]; then 
like image 84
Niklas B. Avatar answered Nov 16 '22 08:11

Niklas B.