我在bash shell中输入命令:
#!/bin/bash
[[ a>2 ]];echo $?
我得到0
和另一个命令:
#!/bin/bash
[[ 3>2 ]];echo $?
我得到了
bash: unexpected token 283 in conditional command
bash: syntax error near `3>'
为什么我会犯这个错误?
如何在> <
中使用[[ ]]
?
我更加好奇,[[]]
如何使用> <
。 [[ a>2 ]];echo $?
不添加空格,但[[ 3 > 2 ]]
必须添加空格,对原因更加好奇
答案 0 :(得分:1)
由于bash builtins的手册页指出:&#34;每个运算符和操作数 必须是一个单独的论点。&#34;
此外,您的变量a
应为$a
以下是示例:
# Returns true
$ a=10; [[ "$a" -gt 1 ]]; echo "$?"
0
# Returns false
$ a=10; [[ "$a" -gt 12 ]]; echo "$?"
1
以下内容可以帮助您
整数比较运算符
| Operator | Description | Example |
|----------|-----------------------------|----------------------------------------------------------|
| -eq | Is Equal To | if [ $1 -eq 200 ] |
| -ne | Is Not Equal To | if [ $1 -ne 1 ] |
| -gt | Is Greater Than | if [ $1 -gt 15 ] |
| -ge | Is Greater Than Or Equal To | if [ $1 -ge 10 ] |
| -lt | Is Less Than | if [ $1 -lt 5 ] |
| -le | Is Less Than Or Equal To | if [ $1 -le 0 ] |
| == | Is Equal To | if (( $1 == $2 )) [Note: Used within double parentheses] |
| != | Is Not Equal To | if (( $1 != $2 )) |
| < | Is Less Than | if (( $1 < $2 )) |
| <= | Is Less Than Or Equal To | if (( $1 <= $2 )) |
| > | Is Greater Than | if (( $1 > $2 )) |
| >= | Is Greater Than Or Equal To | if (( $1 >= $2 )) |
字符串比较运算符
| Operator | Description | Example |
|----------|------------------------------------|-----------------|
| = or == | Is Equal To | if [ $1 == $2 ] |
| != | Is Not Equal To | if [ $1 != $2 ] |
| > | Is Greater Than (ASCII comparison) | if [ $1 > $2 ] |
| >= | Is Greater Than Or Equal To | if [ $1 >= $2 ] |
| < | Is Less Than | if [ $1 < $2 ] |
| <= | Is Less Than Or Equal To | if [ $1 <= $2 ] |
| -n | Is Not Null | if [ -n $1 ] |
| -z | Is Null (Zero Length String) | if [ -z $1 ] |