0

My first question is why putting ! in the front of if statement fails to produce syntax error when status is not double quoted. That is how is [ ! $x = "string" ] different from [ $x != "string" ]?

My script is as follows.

#!/bin/bash status=" " # Comparison 1: without error echo "-----Comparison 1-----" if [ ! $status = "success" ] then echo 'Error: status was not success but: ' $status else echo "The status is success." fi echo "-----Comparison 2-----" # Comparison 2: with error message but still shows success if [ $status != "success" ] then echo 'Error: status was not success but: ' $status else echo "The status is success." fi echo "-----Comparison 3-----" # Comparison 3: Correct result after quoting status if [ ! "$status" == "success" ] then echo 'Error: status was not success but: ' $status else echo "The status is success." fi echo "-----Comparison 4-----" # Comparison 4: Correct result after quoting status if [ "$status" != "success" ] then echo 'Error: status was not success but: ' $status else echo "The status is success." fi 

The output is

-----Comparison 1----- The status is success. -----Comparison 2----- ./test2.sh: line 14: [: !=: unary operator expected The status is success. -----Comparison 3----- Error: status was not success but: -----Comparison 4----- Error: status was not success but: 

Additional questions

  • Why does it produce "The status is success." in Comparison 2 after a syntax error? How would a syntax error in an if statement affects the evaluated result of such if statement?

p.s. I know we need "" around $status to make output right.

2
  • 3
    Use [[ .. ]] instead of [ .. ] Commented Oct 1, 2018 at 14:29
  • 1
    @anubhava thanks for the suggestion. Commented Oct 1, 2018 at 14:34

1 Answer 1

2

You need to quote $status. Without the quotes, your first comparison is

if [ ! = "success" ] 

which will fail because ! and success are not equal strings.

Your second one results in a syntactically invalid expression for [:

if [ != "success" ] 

The syntax error you see in condition 2 isn't a shell syntax error, but a condition syntax error raised by the [ command. The command itself runs fine, but exits with a non-zero exit status.

Sign up to request clarification or add additional context in comments.

3 Comments

Why in the first scenario, it still produces success?
Because success means the condition did not hold, and ! = success is indeed false. ! isn't an operator in this context; it's just the left-hand operand of the = operator.
Oh I see. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.