Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing a number and adding a leading zero in Bash

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.

like image 562
CptSupermrkt Avatar asked Apr 23 '13 23:04

CptSupermrkt


3 Answers

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.

like image 91
Jacob Avatar answered Oct 11 '22 13:10

Jacob


A short solution without 'case':

((cursorDay++))                   # increment
cursorDay=0$cursorDay             # add leading 0
echo  "${cursorDay: -2}"          # echo last 2 characters
like image 25
Fritz G. Mehner Avatar answered Oct 11 '22 13:10

Fritz G. Mehner


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)
like image 24
suspectus Avatar answered Oct 11 '22 13:10

suspectus