为什么要周围有空格' ['和']'在狂欢中?

发布于 2025-01-29 21:59:59 字数 185 浏览 2 评论 0原文

我试图编写一个使用语句的bash脚本。

if[$CHOICE -eq 1];

该脚本给我错误,直到我在之前和之后给出一个空间[

if [ $CHOICE -eq 1 ];

]在狂欢中很重要?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

秋叶绚丽 2025-02-05 21:59:59

一旦您掌握了 [ 命令 ,一个批次就变得更加清晰了!

[ 是拼写“ test”的另一种方法。

help [

但是,尽管它们完全相同 test事实证明有一个更详细的帮助页面。检查

help test

...以获取更多信息。


此外,请注意,我故意使用帮助测试而不是MAN TEST。那是因为test[是如今的壳命令。他们的功能集可能不同于/bin/test/bin/[的coreutils,这是man页面中所述的命令。

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.

姜生凉生 2025-02-05 21:59:59

来自另一个问题

有些历史:这是因为'['历史上不是壳牌制造的,而是一个单独的可执行文件,它作为参数并返回结果。如果您没有包围“ [''空间,shell将搜索$路径以获取其他文件名(并且找不到)。 - Andrew Medico 09年6月24日,1:13

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

断舍离 2025-02-05 21:59:59

[是命令,$ opeach应该是一个参数,但是通过执行[$ opeach>之间没有任何空间[和$选择)您正在尝试运行一个名为的命令[$选择。命令的语法是:

command arguments separated with space

[ 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
安人多梦 2025-02-05 21:59:59

[test命令。因此需要空间。

[ is a test command. So it requires space.

埋葬我深情 2025-02-05 21:59:59

值得注意的是,[也用于地球匹配,这可能会使您陷入困境。

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文