我正在读一些关于if
但是,有些示例是用单个方括号编写的:
if [ -f $param ]
then
#...
fi
其他有两个方括号的国家:
if [[ $? -ne 0 ]]
then
start looking for errors in yourlog
fi
有什么不同?
发布于 2018-04-16 08:58:53
单株[]
符合POSIX外壳的条件测试。
双倍[[]]
是对标准的扩展[]
并由bash和其他shell(例如zsh、ksh)支持。它们支持额外的操作(以及标准的POSIX操作)。例如:||
而不是-o
和正则表达式匹配=~
。更全面的差异列表可以在关于条件构造的Bash手册部分。
使用[]
每当希望脚本跨shell可移植时。使用[[]]
如果希望条件表达式不受[]
也不需要携带。
发布于 2018-04-16 09:43:18
关于Bash 4.3.11的一些不同之处:
- `[` [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
建议*总是使用[]
。
每个[[ ]]
我见过的建筑。
如果你用[[ ]]
你:
[
只是一个带有奇怪名称的常规命令,不涉及特殊的语义。https://stackoverflow.com/questions/-100003875
复制相似问题