如何使用带前导零的数字的变量执行bash算术运算? [英] How can I do bash arithmetic with variables that are numbers with leading zeroes?

查看:39
本文介绍了如何使用带前导零的数字的变量执行bash算术运算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在bash脚本中有以下代码,其中值"是用换行符分隔的数字的变量,其中一些以前导0开头,我正在尝试遍历值中的每个值并将每个值添加到变量"sum".

I have the following code in a bash script, where "values" is a variable of newline separated numbers, some of which have leading 0's, and I am trying to iterate through each value in values and add each value to the variable "sum".

sum=0
while read line; do
    sum=$(( sum + line ))
done <<< "$values"

此代码段给我一个错误:值对于基数太大(错误标记为"09"),据我了解,这是因为bash算术表达式将值"line"解释为八进制值,因为它有一个前导零.

this code segment gives me the error: "value too great for base (error token is "09")", which as I understand, is because the bash arithmetic expression interprets the value "line" to be an octal value because it has a leading zero.

我如何允许bash将line的值解释为其十进制值?(例如09-> 9)该bash算术表达式中的值"line"?

How can I allow for bash to interpret the value of line to be its decimal value? (e.g. 09 -> 9) for the value "line" within this bash arithmetic expression?

推荐答案

您可以通过使用 10#显式强制以10为基数来覆盖前导0表示八进制":

You can override the "leading 0 means octal" by explicitly forcing base ten with 10#:

sum=$(( 10#$sum + 10#$line ))

请注意,尽管通常可以在算术上下文中将 $ 保留在变量引用之外,但在这种情况下,则需要它.另外,如果该变量的前导空格(在第一个"0"之前),则将无法正确解析.

Note that, while you can usually leave the $ off variable references in arithmetic contexts, in this case you need it. Also, if the variable has leading spaces (in front of the first "0"), it won't parse correctly.

这篇关于如何使用带前导零的数字的变量执行bash算术运算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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