在 Bash 中增加一个数字并添加一个前导零

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16180774/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:15:49  来源:igfitidea点击:

Incrementing a number and adding a leading zero in Bash

bashunixleading-zero

提问by CptSupermrkt

The problem is with the numbers 08 and 09. I've Googled this and found out the reason that 08 and 09 are problematic, but no solution.

问题出在数字 08 和 09 上。我在谷歌上搜索了这个,发现了 08 和 09 有问题的原因,但没有解决方案。

This is a nonsensical example used to briefly describe my problem without getting into the details.

这是一个荒谬的例子,用于简要描述我的问题而不深入细节。

cursorDay=2;
let cursorDay=$cursorDay+1;

case "$cursorDay" in

1) cursorDay=01;;
2) cursorDay=02;;
3) cursorDay=03;;
4) cursorDay=04;;
5) cursorDay=05;;
6) cursorDay=06;;
7) cursorDay=07;;
8) cursorDay=08;;
9) cursorDay=09;

esac

echo "$cursorDay";

The output I expect is "03", and indeed I do get that output. But if I do the same thing to try and get 08 or 09, I this error:

我期望的输出是“03”,确实我得到了那个输出。但是,如果我做同样的事情来尝试获得 08 或 09,则会出现此错误:

line 100: let: cursorDay=08: value too great for base (error token is "08")

The question is, is there any way to "force" it to treat 08 and 09 as just regular numbers? I found several posts detailing how to eliminate the zero, but I wanta zero.

问题是,有没有办法“强制”将 08 和 09 视为普通数字?我找到了几篇详细介绍如何消除零的帖子,但我想要一个零。

回答by Jacob

When you evaluate arithmetic expressions (like let does), a leading 0 indicates an octal number. You can force bash to use a given base by prefixing base#to the number. In addition, you can use printf to pad numbers with leading zeroes.

当您计算算术表达式时(就像 let 那样),前导 0 表示八进制数。您可以通过在数字前加上base#来强制 bash 使用给定的 base 。此外,您可以使用 printf 用前导零填充数字。

So your example could be rewritten as

所以你的例子可以改写为

cursorDay=2

let cursorDay=10#$cursorDay+1
printf -v cursorDay '%02d\n' "$cursorDay"

echo "$cursorDay"

or even shorter as

甚至更短

cursorDay=2

printf -v cursorDay '%02d\n' $((10#$cursorDay + 1))

echo "$cursorDay"

Please note that you cannot omit the $between the #and the variable name.

请注意,不能省略和 变量名$之间的#

回答by Fritz G. Mehner

A short solution without 'case':

没有“案例”的简短解决方案:

((cursorDay++))                   # increment
cursorDay=0$cursorDay             # add leading 0
echo  "${cursorDay: -2}"          # echo last 2 characters

回答by suspectus

Just prefix the number with '0'.

只需在数字前面加上“0”即可。

cursorDay=2;
let cursorDay=$cursorDay+1;

case "$cursorDay" in   
1) cursorDay=1;;
2) cursorDay=2;;
3) cursorDay=3;;
4) cursorDay=4;;
5) cursorDay=5;;
6) cursorDay=6;;
7) cursorDay=7;;
8) cursorDay=8;;
9) cursorDay=9;;  
esac  
echo "0$cursorDay";

OR

或者

     case
     ...
    7) cursorDay="07";;
    8) cursorDay="08";;
    9) cursorDay="09";;  

let numericValue=$(expr $cursorDay + 0)