1

Suppose that a=$((1))

How can I change the value of a from 1 to 01? I just want to insert the 0 before the current value of a and rewrite it.

a=$((01)) would not be a solution in this case because a can be any one-digit number, not necessarily 1. That would be hard-wiring the code. I want the variable a to be updated automatically.

1

It's as simple as a=0"$a" which precedes the content of $a with a '0'.

4

You can treat a as a string, so prepending "0" to it will work:

a="0$a"

You can also format a as a string with a defined number of digits. For example, with two-digit formatting, numbers 0-9 would have a leading zero added but numbers 10-99 would not:

a=$(printf "%02d" $a)

Be aware that when adding together numbers that have leading zeros, you'll end up using octal arithmetic rather than decimal. As an example, this probably won't do what you might have expected:

a=08
echo $(( a + 1 ))
  • I know within Vim there's a workaround for Vim's similar octal arithmetic issue...is there such a workaround for the shell? – Wildcard May 5 '16 at 23:24
  • 1
    @Wildcard ${a//0} will strip all leading zeros, so a=08; echo $(( ${a//0} + 1 )) will result in 9 – roaima May 6 '16 at 12:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.