Bash – Increment Decimal Variable with Leading Zero by +1

arithmeticbashnumeric datashell-script

I have a file in the name of Build.number with the content value 012 which I need to increment by +1.
So, I tried this

BN=$($cat Build.number)
BN=$(($BN+1))
echo $BN >Build.number

but here I am getting the value 11 when I am expecting 013.
Can anyone help me?

Best Answer

The leading 0 causes Bash to interpret the value as an octal value; 012 octal is 10 decimal, so you get 11.

To force the use of decimal, add 10# (as long as the number has no leading sign):

BN=10#$(cat Build.number)
echo $((++BN)) > Build.number

To print the number using at least three digits, use printf:

printf "%.3d\n" $((++BN)) > Build.number
Related Question