Hei*_*nzi 15 bash variable-substitution
#!/bin/bash
VALUE=10
if [[ VALUE -eq 10 ]]
then
echo "Yes"
fi
Run Code Online (Sandbox Code Playgroud)
令我惊讶的是,这输出“是”。我原以为它需要[[ $VALUE -eq 10 ]]. 我已经扫描了 的CONDITIONAL EXPRESSIONS部分man bash,但没有找到任何可以解释这种行为的内容。
rus*_*ush 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.
Run Code Online (Sandbox Code Playgroud)
例如:
[[ hdjakshdka -eq fkshdfwuefy ]]
Run Code Online (Sandbox Code Playgroud)
将始终返回 true
但是这个会返回错误
$ [[ 1235hsdkjfh -eq 81749hfjsdkhf ]]
-bash: [[: 1235hsdkjfh: value too great for base (error token is "1235hsdkjfh")
Run Code Online (Sandbox Code Playgroud)
也可以使用递归:
$ VALUE=VALUE ; [[ VALUE -eq 12 ]]
-bash: [[: VALUE: expression recursion level exceeded (error token is "VALUE")
Run Code Online (Sandbox Code Playgroud)