为什么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

相关阅读:

相关推荐
17(无规则自律)2 分钟前
【Linux驱动实战】:字符设备之ioctl与mutex全解析
linux·c语言·驱动开发·嵌入式硬件
CDN36019 分钟前
360CDN SDK 游戏盾:轻量化接入 + 强防护实测
运维·游戏·网络安全
Stewie1213822 分钟前
Docker 面试题
运维·docker·容器
星纬智联技术1 小时前
GEO E2E 自动化验证测试文章
运维·自动化·geo
天赐学c语言1 小时前
Linux - 应用层自定义协议与序列/反序列化
linux·服务器·网络·c++
jarreyer1 小时前
CentOS 7 无法使用 yum 安装软件
linux·运维·centos
脆皮的饭桶2 小时前
结合使用,实现IPVS的高可用性、利用VRRP Script 实现全能高可用
运维·服务器·网络
薛定谔的悦3 小时前
告别传统BMS!深度解读阳光电源 BM^2T 电池管理技术白皮书
linux·能源·储能·bms·ems
源远流长jerry3 小时前
DPDK MP (Multi-Process) 通道深度解析
linux·网络·架构·ip
RisunJan3 小时前
Linux命令-md5sum(计算和校验文件报文摘要的工具程序)
linux·运维