Bash中单方括号和双方括号的区别 [英] Difference between single and double square brackets in Bash

查看:51
本文介绍了Bash中单方括号和双方括号的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关 if 的 bash 示例,但有些示例是用单方括号编写的:

I'm reading bash examples about if but some examples are written with single square brackets:

if [ -f $param ]
then
  #...
fi

其他方括号:

if [[ $? -ne 0 ]]
then
    start looking for errors in yourlog
fi

有什么区别?

推荐答案

单个 [] 是符合 posix shell 的条件测试.

Single [] are posix shell compliant condition tests.

Double [[]] 是标准 [] 的扩展,并被 bash 和其他 shell(例如 zsh、ksh)支持.它们支持额外的操作(以及标准的 posix 操作).例如:|| 代替 -o 和与 =~ 匹配的正则表达式.更完整的差异列表可以在 bash 手册部分关于条件构造.

Double [[]] are an extension to the standard [] and are supported by bash and other shells (e.g. zsh, ksh). They support extra operations (as well as the standard posix operations). For example: || instead of -o and regex matching with =~. A fuller list of differences can be found in the bash manual section on conditional constructs.

只要您希望脚本可以跨 shell 移植,请使用 [].如果您希望 [] 不支持条件表达式并且不需要可移植,请使用 [[]].

Use [] whenever you want your script to be portable across shells. Use [[]] if you want conditional expressions not supported by [] and don't need to be portable.

这篇关于Bash中单方括号和双方括号的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆