值对于基数太大(错误令牌为"08") [英] Value too great for base (error token is "08")

查看:120
本文介绍了值对于基数太大(错误令牌为"08")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题是要在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")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆