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

BashIf StatementSyntax

Bash Problem Overview


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?

Bash Solutions


Solution 1 - Bash

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.

Solution 2 - Bash

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

Solution 3 - Bash

[ 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

Solution 4 - Bash

[ is a test command. So it requires space.

Solution 5 - Bash

It's worth noting that [ is also used in glob matching, which can get you into trouble.

$ echo [12345]
[12345]
$ echo oops >3
$ echo [12345]
3

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShashView Question on Stackoverflow
Solution 1 - BashjohnsywebView Answer on Stackoverflow
Solution 2 - BashCameronView Answer on Stackoverflow
Solution 3 - BashJahidView Answer on Stackoverflow
Solution 4 - BashPrince John WesleyView Answer on Stackoverflow
Solution 5 - BashDanielView Answer on Stackoverflow