Tai
Tai

Reputation: 7994

Bash if statement produces different result with exclamation mark in different positions

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

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

Upvotes: 0

Views: 152

Answers (1)

chepner
chepner

Reputation: 531808

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.

Upvotes: 2

Related Questions