Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in bash if statement: Conditional binary operator expected

Tags:

grep

bash

I have an if statement in my bash script as follows:

if [[ eb status my-env-staging-worker | grep 'Green' -ne 0 ] || [ eb status my-env-staging-web | grep 'Green' -ne 0 ]]

Basically if the first or second eb status command dont have the string Green I'd like to execute some other stuff.

However I get the following Error:

Conditional binary operator expected syntax error near status script returned exit code 2

Could you tell me whats wrong?

like image 223
HosseinK Avatar asked Nov 28 '25 11:11

HosseinK


1 Answers

[[ and [ are not for grouping. They're independent commands. Instead of if [[ cmd1 -ne 0 ] || [ cmd2 -ne 0 ]], leave out the brackets and the tests and simply write if cmd1 || cmd2.

if eb status my-env-staging-worker | grep -q 'Green' || eb status my-env-staging-web | grep -q 'Green'

I've added -q to suppress grep's output since you only care about the return code.

If you want to invert the condition, write:

if ! eb status my-env-staging-worker | grep -q 'Green' && ! eb status my-env-staging-web | grep -q 'Green'

or

if ! { eb status my-env-staging-worker | grep -q 'Green' || eb status my-env-staging-web | grep -q 'Green'; }

Here you can see { and } used for grouping. Curly braces and parentheses are bash's grouping tokens.

like image 99
John Kugelman Avatar answered Dec 01 '25 08:12

John Kugelman