Increase the number and add a leading zero in Bash

The problem is with numbers 08 and 09. I looked for it and found out the reason why 08 and 09 are problematic, but there is no solution.

This is a meaningless example, used to briefly describe my problem, without going into 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 result that I expect is "03", and indeed, I get this output. But if I do the same to try to get 08 or 09, I get this error:

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

The question is, is there a way to “force” to handle 08 and 09 as regular numbers? I found several posts detailing how to eliminate zero, but I want zero.

+5
source share
3 answers

(, let ), 0 . bash , base # . , printf .

,

cursorDay=2

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

echo "$cursorDay"

,

cursorDay=2

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

echo "$cursorDay"

, $ # .

+8

"":

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

Just the prefix of 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)
+1
source

All Articles