Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 811
Shash Avatar asked Mar 06 '12 09:03

Shash


People also ask

Does spacing matter in bash?

The lack of spaces is actually how the shell distinguishes an assignment from a regular command. Also, spaces are required around the operators in a [ command: [ "$timer"=0 ] is a valid test command, but it doesn't do what you expect because it doesn't recognize = as an operator.

Is bash space sensitive?

Bash indenting is very sensitive to characters. For example a space behind “do” in while/for loops will throw it of. When you have nested loops this is very ugly, and makes it hard to follow the code.

How do you represent a space in bash?

To cd to a directory with spaces in the name, in Bash, you need to add a backslash ( \ ) before the space. In other words, you need to escape the space.


1 Answers

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.

like image 153
Johnsyweb Avatar answered Sep 22 '22 15:09

Johnsyweb