Incrementing a number and adding a leading zero in Bash

CptSupermrkt picture CptSupermrkt · Apr 24, 2013 · Viewed 8.9k times · Source

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.

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:

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 want a zero.

Answer

Jacob picture Jacob · Apr 24, 2013

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.

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.