Bash中单方括号和双方括号的区别

编程入门 行业动态 更新时间:2024-10-12 20:25:14
本文介绍了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中单方括号和双方括号的区别

本文发布于:2023-10-24 21:02:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524995.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:括号   区别   Bash   单方

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!