在bash脚本中将字符串转换为整数-"Leading Zero"数字错误 [英] Convert string into integer in bash script - "Leading Zero" number error

查看:112
本文介绍了在bash脚本中将字符串转换为整数-"Leading Zero"数字错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在文本文件test.txt中,我有以下信息:

In a text file, test.txt, I have the next information:

sl-gs5 desconnected Wed Oct 10 08:00:01 EDT 2012 1001

我想通过下一个命令行提取事件的时间:

I want to extract the hour of the event by the next command line:

hour=$(grep -n sl-gs5 test.txt | tail -1 | cut -d' ' -f6 | awk -F ":" '{print $1}')

我得到"08".当我尝试添加1时,

and I got "08". When I try to add 1,

 14 echo $((hour+1))

我收到下一条错误消息:

I receive the next error message:

./test2.sh: line 14: 08: value too great for base (error token is "08")

如果Bash中的变量没有类型,为什么?

If variables in Bash are untyped, why?

推荐答案

请参见man bash中的算术评估:

以0开头的常量被解释为八进制数.

Constants with a leading 0 are interpreted as octal numbers.

您可以通过参数扩展删除前导零:

You can remove the leading zero by parameter expansion:

hour=${hour#0}

或以10为基数的解释:

or force base-10 interpretation:

$((10#$hour + 1))

这篇关于在bash脚本中将字符串转换为整数-"Leading Zero"数字错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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