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

问题:

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

if[$CHOICE -eq 1];

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

if [ $CHOICE -eq 1 ];

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


回答:

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

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 以查询更多信息。

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

相关阅读:

相关推荐

  1. 为什么Bash“[““]“周围应该空格

    2024-05-01 07:46:02       27 阅读
  2. [linux] bash单引号(‘)双引号(“)

    2024-05-01 07:46:02       28 阅读
  3. Bash Shell单引号双引号区别详解

    2024-05-01 07:46:02       46 阅读
  4. Linux .bashrc、.bash-profile .profile 之间区别

    2024-05-01 07:46:02       35 阅读
  5. bash通配符小结

    2024-05-01 07:46:02       30 阅读
  6. 去除Bash 变量空白字符 —— 筑梦之路

    2024-05-01 07:46:02       61 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-01 07:46:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-01 07:46:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-05-01 07:46:02       82 阅读
  4. Python语言-面向对象

    2024-05-01 07:46:02       91 阅读

热门阅读

  1. 文献交叉引用,批量上标

    2024-05-01 07:46:02       37 阅读
  2. spannerlib优雅的go异常处理

    2024-05-01 07:46:02       31 阅读
  3. k8s 日常维护命令简介

    2024-05-01 07:46:02       39 阅读
  4. k8s中deployment和StatefulSet构建的pod的区别

    2024-05-01 07:46:02       25 阅读
  5. 【C++之多态的知识】

    2024-05-01 07:46:02       30 阅读
  6. 阿里云详细介绍,与AWS和GCP比较

    2024-05-01 07:46:02       33 阅读
  7. 【测试思考】高覆盖的测试用例不只要方法

    2024-05-01 07:46:02       41 阅读
  8. Harbor服务器停电重启后用户不能登陆怎么办?

    2024-05-01 07:46:02       37 阅读
  9. 文件导入导出【开发实践】

    2024-05-01 07:46:02       41 阅读
  10. 算法二分查找(C语言版)

    2024-05-01 07:46:02       33 阅读
  11. http作业

    2024-05-01 07:46:02       37 阅读