问题描述
这里我的问题是找出在if语句中使用单括号[]和双括号[[]]的区别.
Here my problem is to find the difference of using single bracket [ ] and double brackets [[ ]] in if statement.
#!/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
推荐答案
shell 尝试将 08 解释为八进制数,因为它以零开头.然而,八进制中只允许数字 0-7,因为十进制 8 是八进制 010.因此 08 不是有效数字,这就是错误的原因.
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.
单括号是与 sh 的一种兼容模式",而 sh 不知道八进制数.
Single brackets are kind of "compatibility mode" with sh, and sh does not know about octal numbers.
因此,如果使用单方括号,010"将被解释为 10,而使用双方括号,010"将被解释为 8.
So, if you use single square brackets, "010" will be interpreted as 10, while with double square brackets, "010" will be interpreted as 8.
如果使用单方括号,08"将被解释为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.
您可以使用此处描述的解决方案避免该错误:https://stackoverflow.com/a/12821845/1419315一个>
You can avoid the error by using the solution described here: https://stackoverflow.com/a/12821845/1419315
if [[ ${vara#0} -lt ${varb#0} ]]
或
if [[ $((10#$vara)) -lt $((10#$varb)) ]]
这篇关于基础值太大(错误标记为“08")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!