Does the syntax of not equal matter?

Jimmy_A

When scripting, I usually write my ifs with the following syntax as it is easier for me to understand that what comes next is not true.

if [ ! "$1" = "$2" ]; then

Others say that the way below is better

if [ "$1" != "$2" ]; then

The thing is when I ask why and whether there are any differences no one seems to have any answer.

So, are there any differences between the two syntaxes? Is one of them safer than the other? Or is it just a matter of preference/habit?

Stéphane Chazelas

Beside the cosmetic/preference arguments, one reason could be that there are more implementations where [ ! "$a" = "$b" ] fails in corner cases than with [ "$a" != "$b" ].

Both cases should be safe if implementations follow the POSIX algorithm, but even today (early 2018 as of writing), there are still implementations that fail. For instance, with a='(' b=')':

$ (a='(' b=')'; busybox test "$a" != "$b"; echo "$?")
0
$ (a='(' b=')'; busybox test ! "$a" = "$b"; echo "$?")
1

With dash versions prior to 0.5.9, like the 0.5.8 found as sh on Ubuntu 16.04 for instance:

$ a='(' b=')' dash -c '[ "$a" != "$b" ]; echo "$?"'
0
$ a='(' b=')' dash -c '[ ! "$a" = "$b" ]; echo "$?"'
1

(fixed in 0.5.9, see https://www.mail-archive.com/[email protected]/msg00911.html)

Those implementations treat [ ! "(" = ")" ] as [ ! "(" "text" ")" ] that is [ ! "text" ] (test whether "text" is the null string) while POSIX mandates it to be [ ! "x" = "y" ] (test "x" and "y" for equality). Those implementations fail because they perform the wrong test in that case.

Note that there's yet another form:

! [ "$a" = "$b" ]

That one requires a POSIX shell (won't work with the old Bourne shell).

Note that several implementations have had problems with [ "$a" = "$b" ] (and [ "$a" != "$b" ]) as well and still do like the [ builtin of /bin/sh on Solaris 10 (a Bourne shell, the POSIX shell being in /usr/xpg4/bin/sh). That's why you see things like:

[ "x$a" != "x$b" ]

In scripts trying to be portable to old systems.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related