How to add leading zeros for for-loop in shell?
seq -w
will detect the max input width and normalize the width of the output.
for num in $(seq -w 01 05); do
...
done
At time of writing this didn't work on the newest versions of OSX, so you can either install macports and use its version of seq
, or you can set the format explicitly:
seq -f '%02g' 1 3
01
02
03
But given the ugliness of format specifications for such a simple problem, I prefer the solution Henk and Adrian gave, which just uses Bash. Apple can't screw this up since there's no generic "unix" version of Bash:
echo {01..05}
Or:
for number in {01..05}; do ...; done
Use the following syntax:
$ for i in {01..05}; do echo "$i"; done
01
02
03
04
05
Disclaimer: Leading zeros only work in >=bash-4
.
If you want to use printf
, nothing prevents you from putting its result in a variable for further use:
$ foo=$(printf "%02d" 5)
$ echo "${foo}"
05