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.
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.
A short solution without 'case':
((cursorDay++)) # increment
cursorDay=0$cursorDay # add leading 0
echo "${cursorDay: -2}" # echo last 2 characters
Just prefix the number with '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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With