This post is aimed at helping people write more pedantically correct shell scripts, which I believe is one of life's most noble goals.
This is the correct way to test if two strings are equal in sh or bash using
if [ "$foo" = "$bar" ]
Note that there is only one equals sign. This is documented for the Bash
builtin if you type
help test (note that
[ if just a weird alias for
test). This is also documented in the online Bash manual.
This is also documented in the
man page for
/usr/bin/test. This is how string checking has worked in the shell since the
original versions of Unix.
This is the correct way to test if two strings are equal in bash using
if [[ "$foo" == "$bar" ]]
Note that there are two equals signs. This is more similar syntax to almost
every other procedural programming language, since most of them use
== to test
It turns out that a lot of people are confused by this whole thing. Those people
sometimes end up using the
== syntax with the
[ operator. The bash authors
decided to deviate from the traditional behavior of
/bin/sh and support this
syntax. So if you do this:
if [ "$foo" == "$bar" ]
then this program will run in bash and do a string equality check. However, this
is not documented, and is also in contravention to how the original
works. So if you try to run this program under an implementation like the
Almquist shell, which Debian
/bin/sh as part of the
dash package, then you will get a syntax
If you're interested in increasing the portability of your scripts and not relying on undocumented behavior I encourage you to use the correct syntax when checking string equality in your shell scripts.