Adding 1 to a variable doesn't work as expected (Bash arithmetic)
That's because numbers starting with 0
are treated as Octal by bash
, hence it is doing Octal (Base 8) addition. To get Decimal addition for this structure, you need to explicitly define the Base or not use 00
altogether.
For Decimal, the Base is 10, denoted by 10#
:
$ A="10#0012"
$ echo $((A+1))
13
You may try this command to get the answer:
A="0012"
echo $A + 1 | bc
More information about bc
command can be found here.
bc
man page:
NAME
bc - An arbitrary precision calculator language
SYNTAX
bc [ -hlwsqv ] [long-options] [ file ... ]
DESCRIPTION
bc is a language that supports arbitrary precision numbers with interactive execution of statements. There are some similarities
in the syntax to the C programming language. A standard math library is available by command line option. If requested, the
math library is defined before processing any files. bc starts by processing code from all the files listed on the command line
in the order listed. After all files have been processed, bc reads from the standard input. All code is executed as it is read.
(If a file contains a command to halt the processor, bc will never read from the standard input.)
This version of bc contains several extensions beyond traditional bc implementations and the POSIX draft standard. Command line
options can cause these extensions to print a warning or to be rejected. This document describes the language accepted by this
processor. Extensions will be identified as such.
An alternate method may be to keep your variables as integers and convert them to a string at the end:
A=12
B=$((A+1))
echo $B
13
C=$( printf '%04d' $B )
echo $C
0013
This style of working with integers in math and converting to string for the answer is more intuitive to me as I'm used to BASIC programming. I appreciate Bash doesn't have variable typing like C and BASIC but pretending it does makes me happy.