Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple and ors in if statement bash

Tags:

unix

Hi i am working on somoething , i need to create a if statement which will take multiple variables in '&&' and '||' combination . for now i am trying to this this simple task but i am getting errors 'Command not found'. i want to first && two counts than || it with a flag i set in my code. following is the code i am trying

if [[$pcount -eq 0 ] && [$ucount -eq 0]] ||  [test $flag -eq 1]
then 
do my stuff 
else 
exit 1
fi

thank you in advance.

like image 871
Faizan Tanveer Avatar asked Nov 14 '12 08:11

Faizan Tanveer


2 Answers

You can't nest [ ... ] because [ is a shell command, not a separate syntactic construct. In Bash, you can use the [[ ... ]] syntactic construct which does support nesting, and in portable sh you can use the ( ... ) parentheses for precedence:

if ([ $pcount -eq 0 ] && [ $ucount -eq 0 ]) ||  [ $flag -eq 1 ]

Additional remarks:

  • [test condition] doesn't make sense, since the [ operator is already an alias for test. Write either [ condition ] or test condition.

  • Leave a space before [ and the test, otherwise sh won't recognize the [ as a command name. [ is a command like any other and is not associated with special parsing rules.

like image 185
user4815162342 Avatar answered Sep 28 '22 23:09

user4815162342


In bash, you can do it like this:

if [[ ( $pcount == 0  &&  $ucount == 0 ) || ( $flag == 1 ) ]]
then
    echo "do stuff"
fi

Alternatively:

if [ "$pcount" -eq 0 -a "$ucount" -eq 0 ] || [ "$flag" -eq 1 ]
then
     echo "do stuff"
fi

But, I would recommend the first approach.

like image 45
dogbane Avatar answered Sep 29 '22 00:09

dogbane