How to add leading zeros for for-loop in shell? [duplicate] How to add leading zeros for for-loop in shell? [duplicate] bash bash

How to add leading zeros for for-loop in shell? [duplicate]


Use the following syntax:

$ for i in {01..05}; do echo "$i"; done0102030405

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


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 printf command to have 0 padding:

printf "%02d\n" $num

Your for loop will be like this:

for (( num=1; num<=5; num++ )); do printf "%02d\n" $num; done0102030405