首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Bash中,单方括号和双方括号有什么区别?

在Bash中,单方括号和双方括号有什么区别?
EN

Stack Overflow用户
提问于 2018-04-16 00:24:11
回答 2查看 0关注 0票数 0

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

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

其他有两个方括号的国家:

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

有什么不同?

EN

回答 2

Stack Overflow用户

发布于 2018-04-16 08:58:53

单株[]符合POSIX外壳的条件测试。

双倍[[]]是对标准的扩展[]并由bash和其他shell(例如zsh、ksh)支持。它们支持额外的操作(以及标准的POSIX操作)。例如:||而不是-o和正则表达式匹配=~。更全面的差异列表可以在关于条件构造的Bash手册部分。

使用[]每当希望脚本跨shell可移植时。使用[[]]如果希望条件表达式不受[]也不需要携带。

票数 0
EN

Stack Overflow用户

发布于 2018-04-16 09:43:18

关于Bash 4.3.11的一些不同之处:

  • POSIX诉Bash扩展:
- `[` [is POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html)
- `[[` is a Bash extension

  • 常规命令与魔法
- `[` is just a regular command with a weird name. 

  • <
- `[[ a < b ]]`: lexicographical comparison
- `[ a \< b ]`: Same as above. `\` required or else does redirection like for any other command. Bash extension.
- I could not find a POSIX alternative to this, see: [How to test strings for less than or equal?](https://stackoverflow.com/questions/21294867/how-to-test-strings-for-less-than-or-equal)

  • &&||
- `[[ a = a && b = b ]]`: true, logical and
- `[ a = a && b = b ]`: syntax error, `&&` parsed as an AND command separator `cmd1 && cmd2` 
- `[ a = a -a b = b ]`: equivalent, but deprecated by POSIX
- `[ a = a ] && [ b = b ]`: POSIX recommendation

  • (
- `[[ (a = a || a = b) && a = b ]]`: false
- `[ ( a = a ) ]`: syntax error, `()` is interpreted as a subshell
- `[ \( a = a -o a = b \) -a a = b ]`: equivalent, but `()` is deprecated by POSIX
- `([ a = a ] || [ a = b ]) && [ a = b ]` POSIX recommendation

  • 分词
- `x='a b'; [[ $x = 'a b' ]]`: true, quotes not needed
- `x='a b'; [ $x = 'a b' ]`: syntax error, expands to `[ a b = 'a b' ]`
- `x='a b'; [ "$x" = 'a b' ]`: equivalent

  • =
- `[[ ab = a? ]]`: true, because it does [pattern matching](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_13) (`* ? [` are magic). Does not glob expand to files in current directory.
- `[ ab = a? ]`: `a?` glob expands. So may be true or false depending on the files in the current directory.
- `[ ab = a\? ]`: false, not glob expansion
- `=` and `==` are the same in both `[` and `[[`, but `==` is a Bash extension.
- `printf 'ab' | grep -Eq 'a.'`: POSIX ERE equivalent
- `[[ ab =~ 'ab?' ]]`: false, loses magic with `''`
- `[[ ab? =~ 'ab?' ]]`: true

  • =~
- `[[ ab =~ ab? ]]`: true, POSIX [extended regular expression](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html#tag_09_04) match, `?` does not glob expand
- `[ a =~ a ]`: syntax error
- `printf 'ab' | grep -Eq 'ab?'`: POSIX equivalent

建议*总是使用[]

每个[[ ]]我见过的建筑。

如果你用[[ ]]你:

  • 失去可移植性
  • 强迫读者了解另一个bash扩展的复杂性。[只是一个带有奇怪名称的常规命令,不涉及特殊的语义。
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100003875

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档