var="$(command1 -l '$var2' -c 'command2|grep -c "search"')"
if [[ var !=0 ]]; then

Why am I getting "conditional binary operator expected". I searched already and. I. see that [[]] is a test statement but why would it not work?

1 Answer 1

  1. You're missing $ in front of var when you call it, like you wrote it, it will be literally var.
  2. Consider possible vulnerabilities of your script when using [[ ... ]] or (( ... )) together with variables you cannot control. In your case, it might be better to use [ "$var" -ne 0 ].
  3. You're missing a space between != and 0 (this is the source of the error!)
  4. != is a string comparison operator, while it might work in your example, you want to use -ne to compare integers.

Make use of shellcheck.

  • Note that (( var !=0 )) would also work here, but like [[ "$var" -ne 0 ]] would be an arbitrary command injection vulnerability if the nature of the output of the command being captured is not under your control. Apr 3, 2020 at 11:13
  • Thanks Stéphane for your insights. Do you consider [[ "$var" -ne 0 ]] unsafe? What about the same without quotes? So, what you think should be preferred?
    – pLumo
    Apr 3, 2020 at 11:16
  • 1
    In [[ $var -ne 0 ]] (with or without the quotes, the quotes being not necessary in this particular case) or (( var!=0 )), the contents of $var is evaluated as an arithmetic expressions and bad things can happen then. [ "$var" -ne 0 ] (the quotes being necessary here as [ is an ordinary command) is safe in bash (but not all other shells), as $var is interpreted as a decimal integer only. [ "$var" != 0 ] (or the [[ $var != 0 ]] kshism) is safe as well but would return true if $var contains 00 as it's a string comparison. Apr 3, 2020 at 13:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .