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

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?

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
iControlEIP
  • 83
  • 1
  • 1
  • 3

1 Answers1

6
  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.

pLumo
  • 22,231
  • 2
  • 41
  • 66
  • 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. – Stéphane Chazelas Apr 03 '20 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 03 '20 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](/q/172103). `[ "$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. – Stéphane Chazelas Apr 03 '20 at 13:32