在bash中修复整数长度时的奇怪行为 [英] strange behavior when fixing integer lengths in bash

查看:156
本文介绍了在bash中修复整数长度时的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的bash脚本中,我设置了以下操作

In my bash script, I set-up the following operations

year=0050
echo $(printf %04d $year)
>0040

我不明白为什么会返回0040 0050.我最终发现要让系统正确打印0050,我将不得不这样做。

I do not understand why 0040 is returned instead of 0050. I eventually found that to get the system to print 0050 correctly, I will have to do this instead.

year=50
echo $(printf %04d $year)
>0050

有没有关于为什么第一种情况发生的见解?

Are there any insights as to why the first case happens?

推荐答案

这是因为带有前导零的数字被Bash解释为八进制,八进制50是十进制40。

It's because numbers with a leading zero are interpreted as octal by Bash, and octal 50 is decimal 40.

要修复它,你可以使用参数扩展来剥离零:

To fix it, you can either strip the zeros with a parameter expansion:

$ printf '%04d\n' "${year##+(0)}"
0050

我放弃了 echo $(...)构造并在格式中插入换行符而不是字符串。

I've dropped the echo $(...) construct and inserted a newline in the formatting string instead.

请注意 +(0)模式需要 \\ textglob shell选项( shopt -s \\ textglob )。

Notice that the +(0) pattern requires the extglob shell option (shopt -s extglob).

或者(更便携),您可以先用算术扩展转换数字:

Alternatively (and more portably), you can convert the number with an arithmetic expansion first:

% printf '%04d\n' "$(( 10#$year ))"
0050

这使用 base n 表示 n (在我们的例子中: $ year )的表示法是基数10而不是八进制。

This uses the base#n notation to indicate that n (in our case: $year) is in base 10 and not octal.

这篇关于在bash中修复整数长度时的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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