Naveen Reddy CH
Naveen Reddy CH

Reputation: 839

Adding two numbers in unix

I tried to add two numbers by below logic:

num=0001
newnum=`expr $num + 1`
echo $newnum

But it returns '2', my desired output is '0002'.

num=0001
newnum=`expr $num + 0001`
echo $newnum

I used above logic also,but no use. What is needed here to get my desired output.
Thanks in advance.

Upvotes: 0

Views: 1108

Answers (3)

dogbane
dogbane

Reputation: 274612

Numbers with leading zeros are interpreted as octal numbers. In order to treat them as decimals you need to prepend 10# to the number. Finally, use printf to pad the number with zeros.

num=0001
newNum=$((10#$num + 1))
paddedNum=$(printf %04d $newNum)

Upvotes: 0

Barmar
Barmar

Reputation: 780994

Use printf to print numbers with leading zeroes:

printf "%04d\n" $num

You shouldn't do arithmetic with numbers with leading zeroes, because many applications treat an initial zero as meaning that the number is octal, not decimal.

Upvotes: 2

devnull
devnull

Reputation: 123508

Use printf:

$ num=0001
$ printf "%04d" $(expr $num + 1)
0002

In order to assign the result to a variable, say:

$ newnum=$(printf "%04d" $(expr $num + 1))
$ echo $newnum
0002

Upvotes: 1

Related Questions