bash 基础值太大(错误标记为“08”)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24777597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Value too great for base (error token is "08")
提问by Thaangaraj
Here my problem is to find the difference of using single bracket [ ] and double brackets [[ ]] in if statement.
这里我的问题是找到在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
回答by JohnB
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.
Shell 尝试将 08 解释为八进制数,因为它以零开头。但是,八进制中只允许数字 0-7,因为十进制 8 是八进制 010。因此 08 不是有效数字,这就是错误的原因。
Single brackets are kind of "compatibility mode" with sh, and sh does not know about octal numbers.
单括号是 sh 的一种“兼容模式”,而 sh 不知道八进制数。
So, if you use single square brackets, "010" will be interpreted as 10, while with double square brackets, "010" will be interpreted as 8.
因此,如果您使用单方括号,“010”将被解释为 10,而使用双方括号,“010”将被解释为 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.
如果使用单方括号,“08”将被解释为 8,而使用双方括号,则它不是有效数字并导致错误。
You can avoid the error by using the solution described here: https://stackoverflow.com/a/12821845/1419315
您可以使用此处描述的解决方案来避免该错误:https: //stackoverflow.com/a/12821845/1419315
if [[ ${vara#0} -lt ${varb#0} ]]
or
或者
if [[ $((10#$vara)) -lt $((10#$varb)) ]]