值对于基数来说太大(错误标记是“08”)

这里我的问题是找出 if 语句中使用单括号[]和双括号[[]]的区别。

#!/bin/bash
vara=08;
varb=10;


## single bracket in if statment is working.
if [ $vara -lt $varb ]; then
echo "yes";
else
echo "no";
fi




## double brackets in if statment is not working; throwing an error like below.
## [[: 08: value too great for base (error token is "08")
if [[ $vara -lt $varb ]]; then
echo "yes";
else
echo "no";
fi
131224 次浏览

The shell tries to interpret 08 as an octal number, as it starts with a zero. Only digits 0-7 are, however, allowed in octal, as decimal 8 is octal 010. Hence 08 is not a valid number, and that's the reason for the error.

Single brackets are kind of "compatibility mode" with sh, and sh does not know about octal numbers.

So, if you use single square brackets, "010" will be interpreted as 10, while with double square brackets, "010" will be interpreted as 8.

If you use single square brackets, "08" will be interpreted as 8, while with double square brackets, it is not a valid number and leads to an error.

You can avoid the error by using the solution described here: https://stackoverflow.com/a/12821845/1419315

if [[ ${vara#0} -lt ${varb#0} ]]

or

if [[ $((10#$vara)) -lt $((10#$varb)) ]]