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."inComparison 2after 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.
[[ .. ]]instead of[ .. ]