This is my bash script – I just want to left-pad a set of numbers with zeroes:
printf "%04d" "09"
printf "%04d" "08"
printf "%04d" "07"
printf "%04d" "06"
Output:
./rename.sh: line 3: printf: 09: invalid number
0000
./rename.sh: line 4: printf: 08: invalid number
0000
0007
0006
What…?
Only 09 and 08 are causing the problem: every other number in my sequence seems to be OK.
If you have your
"09"in a variable, you can doWhy does this help? Well, a number literal starting with
0but having noxat the 2nd place is interpreted as octal value.Octal value only have the digits
0..7,8and9are unknown."${a#0}"strips one leading0. The resulting value can be fed toprintfthen, which prints it appropriately, with0prefixed, in 4 digits.If you have to expect that you get values such as
"009", things get more complicated as you’ll have to use a loop which eliminates all excess0s at the start, or anextglobexpression as mentioned in the comments.