检查bash手册页上Compound Commands
的部分。具体而言,以下几点:
((expression))
The expression is evaluated according to the rules described below
under ARITHMETIC EVALUATION. If the value of the expression is non-zero,
the return status is 0; otherwise the return status is 1. This is exactly
equivalent to `let "expression"`.
[[ 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.
如果您正在评估需要运算,使用算术运算评估,并检查CONDITIONAL EXPRESSIONS
节你可以用[[ ... ]]
做各种事情的东西。双方括号中的条件可以评估字符串和整数,有时候它们的工作方式是相同的,有时候不会。
从bash的手册页,下CONDITIONAL EXPRESSIONS
:
string1 == string2
string1 = string2
True if the strings are equal. = should be used with the test command for POSIX conformance. When used with the [[ command, this performs pattern
matching as described above (Compound Commands).
...
arg1 OP arg2
OP is one of -eq, -ne, -lt, -le, -gt, or -ge. These arithmetic binary operators return true if arg1 is equal to, not equal to, less than, less than
or equal to, greater than, or greater than or equal to arg2, respectively. Arg1 and arg2 may be positive or negative integers.
显然,字符串 “1” 是字符串 “1”,所以如果n=1
,和你比较$n
对字符串"1"
,你会得到一击。但是你应该知道你在做什么,而这不是一个数字比较。同样,<
和>
不是数字比较,它们是字符串比较。所以虽然"1" < "2"
,你也可能会惊讶"11" < "2"
以及。
也就是说,bash的是宽容有关什么样的条件,你问它来评价:
bash-4.4$ n=1
bash-4.4$ [[ n -eq 1 ]] && echo yes
yes
bash-4.4$ [[ $n -eq 1 ]] && echo yes
yes
bash-4.4$ ((n == 1)) && echo yes
yes
bash-4.4$ ((n = 2)) && echo yes
yes
bash-4.4$ echo "$n"
2
的第一个作品,因为n
不能是什么,但在这种情况下一个变量,所以庆典将把它因此。但是你不应该依赖这种行为。在条件表达式中使用美元符号作为变量,并坚持使用bash的口头禅,“总是引用你的变量”。
在bash中的双方括号表达式中,如果打算比较为整数,则应使用算术二元运算符。
请注意,您的busybox版本似乎使用ash
,这不是bash
。 Ash是“Almquist shell”,是80年代后期写成的比POSIX更早的POSIX shell。 Ash是FreeBSD中的/bin/sh
的基础,除了在嵌入式系统(因此busybox)中比bash更受欢迎之外,由于其体积较小。
您可能需要考虑编写POSIX shell脚本而不是Bash shell脚本。这将意味着简化一些事情,并为其他人跳过一些箍。 POSIX不包括双方括号表达式,但它确实允许诸如[ "$n" -eq 1 ]
或[ $((n + 1)) -eq 2 ]
之类的东西。它会在busybox中工作。 :)
'if [[var -eq 1]];然后回显“OK”;否则回显“失败”; fi'在'bash'和'ksh'上为我打印'失败' – anubhava
@anubhava .. echo $ var返回什么? :) – ghoti
'declare -p var'显示我 '-bash:declare:var:not found' – anubhava