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

相关阅读:

相关推荐
ShineWinsu3 小时前
对于Redis:Redis的认识以及分布式系统的解析
linux·数据库·c++·redis·缓存·消息队列·分布式架构
Zenova EdgeOS3 小时前
Linux IO 监测:iotop 工业边缘排障实战
linux·边缘计算·工业网关·iotop·排障
Fcy6483 小时前
Linux下 传输层协议UDP详解(含底层源码解析)
linux·运维·udp
青梅味猪大肠3 小时前
【操作系统-24】双标志先检查
linux·运维·服务器
xiaoye-duck3 小时前
《Linux 网络编程》深入理解五种 IO 模型:从 IO 本质到非阻塞 IO 实战
linux·网络
程序员-Benothing3 小时前
Linux内核与模块管理:uname、lsmod、modprobe、sysct
linux·运维·数据库
微三云生态系统架构师-彭丹3 小时前
智慧物业工单智能派单算法:技能匹配与位置负载均衡设计
运维·负载均衡·物业管理·调度算法·工单系统·智能派单·智慧物业
嵌入式小能手3 小时前
飞凌嵌入式ElfBoard-Shell编程应用实例-使用WiFi拨号上网
linux·服务器·网络
..Dauntless..3 小时前
【Linux】环境变量
linux·运维·服务器
FED_AF4 小时前
Linux运维“邪修”功法之正则表达式
linux·运维·正则表达式