【问题标题】:Difference between conditional expressions using [ and [[使用 [ 和 [[ 的条件表达式之间的区别
【发布时间】:2012-06-29 04:24:01
【问题描述】:

两者之间的确切区别是什么:

if [ $? -ne 0 ];

if [[ $? -ne 0 ]];

【问题讨论】:

  • [ (通常)是程序的名称。这应该有助于解释一些差异。
  • 在 bash 中,[ 是一个内置程序(试试type [),但[ 通常也是一个外部程序。
  • 请看BashFAQ/031
  • 另见this

标签: bash syntax conditional


【解决方案1】:

here所述:

[相反,[[ 防止变量值的分词。因此,如果 VAR="var with spaces",你不需要在测试中双引号 $VAR - 尽管使用引号仍然是一个好习惯。此外,[[ 防止路径名扩展,因此带有通配符的文字字符串不会尝试 展开为文件名。使用 [[==!= 将字符串解释为 正确的外壳 glob 模式与值匹配 左边,例如:[[ "value" == val* ]]

【讨论】:

  • 一个小附录:防止分词和路径名扩展等功能是因为[[ 是内置命令,而[ 是外部命令。
  • @Samveen: [ 是一个外部命令。但它也是内置的。
【解决方案2】:

没有。不过,[[...]] 语法引入了一些您可以使用条件表达式执行的其他操作。来自help [[

Returns a status of 0 or 1 depending on the evaluation of the conditional
expression EXPRESSION.  Expressions are composed of the same primaries used
by the `test' builtin, and may be combined using the following operators:

  ( EXPRESSION )    Returns the value of EXPRESSION
  ! EXPRESSION              True if EXPRESSION is false; else false
  EXPR1 && EXPR2    True if both EXPR1 and EXPR2 are true; else false
  EXPR1 || EXPR2    True if either EXPR1 or EXPR2 is true; else false

When the `==' and `!=' operators are used, the string to the right of
the operator is used as a pattern and pattern matching is performed.
When the `=~' operator is used, the string to the right of the operator
is matched as a regular expression.

【讨论】:

  • 没有,但这里有一些?
  • 是的,[ $? -ne 0 ][[ $? -ne 0 ]]的结果绝对没有区别。
猜你喜欢
  • 2012-06-01
  • 2013-09-18
  • 1970-01-01
  • 2016-07-07
  • 2018-08-22
  • 2021-01-24
  • 2013-12-14
  • 2012-09-24
  • 1970-01-01
相关资源
最近更新 更多