Zero Padding in Bash

April 30th, 2007 § 32 comments § permalink

This is as much a reminder for myself as anything. I needed to create 31 folders named 00 through 31 for each day of the month in a web-directory used to store audio files from CAPE-1 transmissions. The first thought that came to mind was to write a quick one-liner bash command/script to create those folders. So, without much thought, I quickly typed the following into a shell on my web server:

for ((x=1;x<=31;x+=1)); do mkdir $x; done

OK, well that did create 31 directories, but the first 9 were named 1, 2, 3, etc. instead of 01, 02, 03 like I wanted. After a quick search on zero-padding in bash it seemed no one had posted anything about it except to say it was tricky. Being a C programmer before a bash script writer, I thought to myself, “Wouldn’t it be nice if I could use a printf() statement in bash?” Then I remembered that you can, only usually it is used for formatting user interface statements. I could not think of any reason it would not work to deliver the argument to a mkdir statement, so I tried:


$ for ((x=1;x< =31;x+=1)); do mkdir `printf "%02d" $x`; done
$ ls
01 03 05 07 09 11 13 15 17 19 21 23 25 27 29 31
02 04 06 08 10 12 14 16 18 20 22 24 26 28 30

And it works! Breaking the command down gives a standard bash for loop with the mkdir command as the internal command inside the loop. As an argument to the mkdir command, however, is a printf statement which given the formatting prints a zero-padded (the 0 after %) two-character long (the 2 after the 0) integer, x. Remember, the `s are back-ticks (below the tilde on most keyboards), not single quotation marks (‘).

It seems like there should be a better way of doing this, but quickest way I found to add zero padding to a number in bash is to use the provided printf which uses the same formatting as the C language printf statement. More usage and examples are available at the ss64.org bash printf reference page.

Where Am I?

You are currently browsing the linux category at Jonathan Wagner.