为什么没有$的变量展开在表达式中起作用?


15
#!/bin/bash

VALUE=10

if [[ VALUE -eq 10 ]]
then
    echo "Yes"
fi

令我惊讶的是,输出为“是”。我本来期望它需要[[ $VALUE -eq 10 ]]。我已经扫描了的CONDITIONAL EXPRESSIONS部分man bash,但没有找到任何能解释这种行为的信息。

Answers:


11

[[是bash保留字,因此应用特殊的扩展规则(例如算术扩展),而不是使用[。还使用算术二进制运算符-eq。因此,shell查找整数表达式,如果在第一项中找到文本,它将尝试将其扩展为参数。它称为算术扩展,存在于中man bash

RESERVED WORDS
       Reserved words are words that have a special meaning to the shell.  
       The following words are recognized as reserved 
       
       [[ ]]

[[ expression ]]
       Return  a  status  of 0 or 1 depending on the evaluation of 
       the conditional expression expression.  Expressions are 
       composed of the primaries described below under CONDITIONAL 
       EXPRESSIONS.  Word splitting and pathname expansion are not 
       performed on the words between the  [[  and  ]];  tilde 
       expansion, parameter and variable expansion, >>>_arithmetic 
       expansion_<<<, command substitution, process substitution, and 
       quote removal are performed.  

Arithmetic Expansion
       
       The evaluation is performed according to the rules listed below 
       under ARITHMETIC EVALUATION.

ARITHMETIC EVALUATION
       
       Within an expression, shell variables may also be referenced 
       by name without using the parameter expansion syntax.

因此,例如:

[[ hdjakshdka -eq fkshdfwuefy ]]

将始终返回true

但是这个会返回错误

$ [[ 1235hsdkjfh -eq 81749hfjsdkhf ]]
-bash: [[: 1235hsdkjfh: value too great for base (error token is "1235hsdkjfh")

还可以使用递归:

$ VALUE=VALUE ; [[ VALUE -eq 12 ]]
-bash: [[: VALUE: expression recursion level exceeded (error token is "VALUE")

为什么作为保留字意味着要进行算术评估?我找不到任何地方记录的内容
Mikel,2012年


man bash为了清楚起见,我在答案中加入了引文。
2012年

@Mikel不是直接[[保留字的事实,而是因为里面的[[ … ]]内容不是普通的命令语法,而是条件表达式。在条件表达式中,诸如的算术运算符的参数要-eq经过算术评估。
吉尔斯(Gilles)'所以

是。我说的第一句话就是这个想法,这是令人误解的
Mikel,2012年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.