#!/bin/bash
VALUE=10
if [[ VALUE -eq 10 ]]
then
echo "Yes"
fi
令我惊讶的是,这输出“是”。我原以为它需要[[ $VALUE -eq 10 ]]
.我已经扫描了CONDITIONAL EXPRESSIONS
的部分man bash
,但没有找到任何可以解释此行为的内容。
答案1
[[
是 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")