为什么Bash中的“[“和“]“周围应该有空格

问题:

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

bash 复制代码
if[$CHOICE -eq 1];

脚本一直在报错,直到我在 [ 前后并在 ] 之前加了一个空格,如下所示:

bash 复制代码
if [ $CHOICE -eq 1 ];

我的问题是,为什么在 Bash 中方括号周围的空格如此重要?


回答:

在 Bash 环境下,使用命令 help [ 查看方括号的帮助信息:

bash 复制代码
root@linux:~# help [
[: [ arg... ]
    Evaluate conditional expression.

    This is a synonym for the "test" builtin, but the last argument must
    be a literal `]', to match the opening `['.

是用于对表达式求值的。它是内置命令 test 的同义词,使用时其最后一个参数必须是字面量 ],以匹配开头的 [

然而,尽管它们做了完全相同的事情,test 却有一个更详细的帮助页面。使用命令 help test 以查询更多信息。

txt 复制代码
test: test [expr]
    Evaluate conditional expression.

    Exits with a status of 0 (true) or 1 (false) depending on
    the evaluation of EXPR.  Expressions may be unary or binary.  Unary
    expressions are often used to examine the status of a file.  There
    are string operators and numeric comparison operators as well.

    The behavior of test depends on the number of arguments.  Read the
    bash manual page for the complete specification.

根据对 expr 的求值,以0 (true)1 (false)的状态退出。表达式可以是一元或二元的。

一元表达式通常用于检查文件的状态。还有字符串运算符和数字比较运算符。

test 的行为取决于参数的数量。请阅读 bash 手册页 以获取完整的规范。

此外,请注意,我故意使用 help test 而不是 man test。这是因为 test[ 是 shell 的内置命令 。它们的功能集可能与手册页中描述的 coreutils 的 /bin/test/bin/[ 命令不同。


参考:

  • stackoverflow question 9581064

相关阅读:

相关推荐
honey ball4 小时前
R & S的EMI接收机面板
linux·运维·网络
木下-俱欢颜5 小时前
搭建基于chrony+OpenSSL(NTS协议)多层级可信时间同步服务
运维·网络安全·udp·ssl
旧故新长6 小时前
访问 Docker 官方镜像源(包括代理)全部被“重置连接”或超时
运维·docker·容器
柳如烟@6 小时前
在Rocky Linux 9.5上部署MongoDB 8.0.9:从安装到认证的完整指南
linux·运维·mongodb
搬码临时工6 小时前
电脑怎么远程访问服务器?4种常见的简单方法
运维·服务器·网络·异地访问
QQ2740287567 小时前
Kite AI 自动机器人部署教程
linux·运维·服务器·人工智能·机器人·web3
文牧之7 小时前
PostgreSQL 配置设置函数
运维·数据库·postgresql
.小墨迹7 小时前
Apollo学习——planning模块(3)之planning_base
linux·开发语言·c++·学习·自动驾驶
K龙8 小时前
私有资产测绘&安全流水线Shovel
运维·安全·开发·其它
影龙帝皖8 小时前
Linux服务之lvs+keepalived nginx+keepalived负载均衡实例解析
linux·nginx·lvs