0

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.

4
  • Which shell are you using? (type 'echo $SHELL' to find out). Also, look at the "printf" command. Commented Jan 3, 2014 at 9:32
  • What you wrote won't work -- you can't have a space after =. I don't know how you're getting 2 with that code. Commented Jan 3, 2014 at 9:33
  • It is /bin/bash @rojomoke Commented Jan 3, 2014 at 9:39
  • It was a typo error, edited it. @Barmar Commented Jan 3, 2014 at 11:03

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It is working..Thanks for your quick reply. This is the simple and good one!
1

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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.