The equal sign in Bash

From bash scripts by my co-workers I noticed there is a big misunderstanding of using the equals sign in bash if statements.

Should I use one square bracket or two, should I use two equal signs or one?

You could use one [ (square bracket) with one = (equal sign). This is valid in bash and sh.

if [ "$random" = "$example" ]

This is documented for the bash test builtin if you type help test. One square bracket [ is an alias for test. You could also find it in the Bash manual. This will work in most shells since the original version of Unix.

The official bash way is to use two [[ (square brackets) and two == (equal signs). It matches the syntax of most other programming languages.

if [[ "$random" == "$example" ]]

Now the biggest mess starts, because bash also supports one square bracket and two equal signs.

if [ "$random" == "$example" ]

The bash authors decided to deviate from the traditional behaviour of /bin/sh and support this syntax. Anyway, this feature is not documented and it will not work on sh and it's derivates. For example dash which is default on Ubuntu will through an syntax error.

If you consider to use your shell script on different systems you should not use the undocumented function :-)


February 26, 2016, 12:21 pm


, , , ,




Send your comment by mail.