Categories
bash if-statement syntax

Why should there be spaces around ‘[‘ and ‘]’ in Bash?

79

I was trying to write a Bash script that uses an if statement.

if[$CHOICE -eq 1];

The script was giving me errors until I gave a space before and after [ and before ] as shown below:

if [ $CHOICE -eq 1 ];

My question here is, why is the space around the square brackets so important in Bash?

6

  • 7

    The general syntax is if command; then commands_if_exit_code_is_0; else commands_if_exit_code_is_nonzero; fi;. command can be any command, and [ is just one of them.

    – Benoit

    Mar 6, 2012 at 9:43

  • 1

    Related: stackoverflow.com/questions/4977367/… (you need spaces around the operator, too).

    – tripleee

    Oct 2, 2017 at 4:37

  • 1

  • 1

    If $CHOICE is "foo", you are attempting to run the command ["foo".

    – tripleee

    Jan 30, 2020 at 18:20

  • 1

    In Bash, [[ obeys the same requirements; you need spaces on both sides, and the command needs to end with ]]. The doubled version is somewhat more versatile and robust; see the link by @codeforester above for a more nuanced discussion.

    – tripleee

    Mar 30, 2021 at 4:24

94

Once you grasp that [ is a command, a whole lot becomes clearer!

[ is another way to spell “test“.

help [

However while they do exactly the same, test turns out to have a more detailed help page. Check

help test

…for more information.


Furthermore note that I’m using, by intention, help test and not man test. That’s because test and [ are shell builtin commands nowadays. Their feature set might differ from /bin/test and /bin/[ from coreutils which are the commands described in the man pages.

2

  • 7

    and originally, it was at /usr/bin/[ and was a hardlink to /usr/bin/test, when invoked as [ you should include a closing brace as last argument. Now it’s a shell builtin.

    – Benoit

    Mar 6, 2012 at 9:41


  • 1

    Note that they are not quite “exactly” the same. [ requires that its last argument be ].

    Jul 15, 2019 at 18:29

18

From another question:

A bit of history: this is because ‘[‘ was historically not a shell-built-in but a separate executable that received the expresson as arguments and returned a result. If you didn’t surround the ‘[‘ with space, the shell would be searching $PATH for a different filename (and not find it) . – Andrew Medico Jun 24 ’09 at 1:13

    9

    [ is a command and $CHOICE should be an argument, but by doing [$CHOICE (without any space between [ and $CHOICE) you are trying to run a command named [$CHOICE. The syntax for command is:

    command arguments separated with space