Why should there be a space after '[' and

2018-12-30 23:39发布

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 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 syntax
4条回答
旧时光的记忆
2楼-- · 2018-12-31 00:09

[ 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
查看更多
旧时光的记忆
3楼-- · 2018-12-31 00:19

[ is a test command. So it requires space.

查看更多
余欢
4楼-- · 2018-12-31 00:20

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

查看更多
不流泪的眼
5楼-- · 2018-12-31 00:27

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.

查看更多
登录 后发表回答