0

Where it worked...

tt=0000005

echo $((tt))

tt=$(($tt+1))

echo $((tt))

5

6

Somewhere it stopped working...

tt=0056505

echo $((tt))

tt=$(($tt+1))

echo $((tt))

23877

23878

Elrik
  • 25
  • 5
  • 1
    bash interprets numbers that start with "0" as octal, rather than decimal, and 0056505 (octal) = 23877 (decimal). See ["How can I do bash arithmetic with variables that are numbers with leading zeroes?"](https://stackoverflow.com/questions/53075017/how-can-i-do-bash-arithmetic-with-variables-that-are-numbers-with-leading-zeroes) and ["How can I increment a number in a while-loop while preserving leading zeroes (BASH < V4)"](https://stackoverflow.com/questions/21592667/how-can-i-increment-a-number-in-a-while-loop-while-preserving-leading-zeroes-ba). – Gordon Davisson Aug 10 '22 at 03:07
  • 1
    BTW, for incrementing the variable, a simpler way to write it is `((tt++))`. – user1934428 Aug 10 '22 at 06:50
  • @user1934428 `((tt++))` won't work if the initial value of `tt` is, for instance, `08`. – M. Nejat Aydin Aug 10 '22 at 06:56
  • @MNejatAydin: Because `08` is not a number, as explained by Gordon Davisson in his comment above. If you initialize it to `8`, it works. BTW, if you initialize the variable to something like `foobar`, it wouldn't work either. – user1934428 Aug 10 '22 at 07:00

1 Answers1

0

You need to trim the leading zeros first

$ tt=0056505
$ tt=$(echo $tt | sed 's/^[0]*//g')
$ echo $((tt))
56505
$ tt=$(($tt+1))
$ echo $((tt))
56506
WeDBA
  • 343
  • 4
  • 7
  • 1
    You can also say `tt=$(( 10#$tt + 1 ))` to tell bash to interpret `$tt` as a decimal number. – tshiono Aug 10 '22 at 03:18
  • That could be useful. Thx. – Elrik Aug 10 '22 at 04:07
  • Creating a subshell and calling an external program to trim leading `0`s from a shell variable is superfluous. Trimming could be done via shell parameter expansions: `tt=${tt#"${tt%%[^0]*}"}` (instead of `tt=$(echo $tt | sed 's/^[0]*//g')`). Or, in bash, `tt=${tt##+(0)}` after setting the `extglob` shell option by `shopt -s extglob`. – M. Nejat Aydin Aug 10 '22 at 06:48