0

I was trying to do an OR logic in If condition

condition 1 => warning ="" and err_code !=1
OR
condition 2 => threshold =1 and threshold_load_ind=Y and err_code!=1

This is throwing an operator level issue . What is missing in the if code

if [  "$warn" != ""  &&  "$err_ind" != 1  ] || [  $thres_err_ind == 1   &&  $thres_load_ind == "Y"  &&  $err_ind != 1  ];then

error code at line 860

[860]: [: ']' missing
[860]: [: ']' missing

  • @zevzek i changed to if [ [ "$warn" != "" ] && [ "$err_ind" != 1 ]] || [ [ $thres_err_ind == 1 ] && [ $thres_load_ind == "Y" ] && [ $err_ind != 1 ] ] but still has the unknown operator issue – Data girl Sep 30 '21 at 18:49

1 Answers1

4

[ is regular command (with a funny name), not part of the shell syntax. Just to make it look confusingly like a syntax element, it expects to see ] as its last argument. But && and || are part of the shell syntax and they separate commands. So your if-statement has five commands, marked below:

if [ "$warn" != ""  && "$err_ind" != 1  ] ||
   1^^^^^^^^^^^^^^^    2^^^^^^^^^^^^^^^^^

[ $thres_err_ind == 1 && $thres_load_ind == "Y" && $err_ind != 1 ]; 3^^^^^^^^^^^^^^^^^^^^ 4^^^^^^^^^^^^^^^^^^^^^ 5^^^^^^^^^^^^^^

The first one runs [ with the three arguments containing the contents of $warn, !=, and an empty string. There's no ], so the [ command complains. Since it fails, the following command after && doesn't run, but the one after || does, and complains for the similar reason. (If the others would run, they'd probably give you "command not found" errors, since the variables are in command position, and if e.g. err_ind contained 0, the shell would try to run the command 0.)

Also, the shell's && and || operators have equal precedence, so a && bb || c && d acts like ( (a && bb) || c) && d, which is probably not what you want.

So, you need to both add the closing ] before the &&/||, and to group the commands manually:

if { [ ... ] && [ ... ]; } ||
   { [ ... ] && [ ... ] && [ ... ]; }; then ...

or with parentheses, which don't require the pesky ; at the end, but launch subshells, which is a slight performance loss:

if ( [ ... ] && [ ... ] ) ||
   ( [ ... ] && [ ... ] && [ ... ] ); then ...

Or switch to using the [[ test (in Bash/ksh/zsh), which is shell syntax and works with different rules and supports &&/||.

See:

ilkkachu
  • 138,973
  • if { [ "$warn" != "" ] && [ "$err_ind" != 1 ] } || { [ $thres_err_ind == 1 ] && [ $thres_load_ind == "Y" ] && [ $err_ind != 1 ] }; then .............................. i tried this code but now the error is "then " unexpected .Any thoughts on this – Data girl Sep 30 '21 at 19:36