0

I am new to shell scripting. I am trying to increment a number and print it. Instead of incrementing it to 017 it is decrementing it to 15.

My script:

num=016
inc=$((num+1))
echo $inc
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
hazzy
  • 107
  • 1
  • 8
  • 1
    The leading `0` in `016` changes how it's parsed (specifically, making it octal rather than decimal). – Charles Duffy Aug 16 '21 at 16:49
  • ...so, in octal, you have 1 in the 8s place, and 6 in the 1s place, so `1*8+6` gives you 14. Increment it once and you get 15. (And suddenly, I have Tom Lehrer's song "New Math" running through my head). – Charles Duffy Aug 16 '21 at 16:53
  • Note that you did not assign the integer 14 (octal 016 == decimal 14) to `num`; you assigned the string `016`. Only when the value of `num` is used in an arithmetic context (such as inside `$((...))` is the value treated like an integer. Further, the result of `$((...))` is not going to have a leading 0, regardless of what `num` originally contained. You'll have to repad the string value yourself. – chepner Aug 16 '21 at 17:22

0 Answers0