2009-01-04

Padding a Numeric in Bash

I needed to pad a day of the month value to 2 places in a bash script.

This is made easy by the GNU program printf, which is part of standard distributions of Linux. In the following script snippet, the current day of the month is passed from the command invocation (or, if not specified, defaulted to the current day). It is then zero-padded with printf.

TODAY=$(date +%d) if [[ "$1" != "" ]]; then TODAY=$1 fi TODAY=$(printf "%02d" $TODAY) # Zero pad day.

2 comments:

Anonymous said...

Good solution but only works by accident with 2 digits and doesn't work for 3 digit numbers if the number is already zero padded, which COULD cause it to be interpreted as octal IF all the digits are less than 8

Try this:

printf "%03d" $(( 10#$NUM )) )

The 10# prefix forces base 10 interpretation, and the $(( )) normalizes it because printf doesn't like the 10#

Andrew Ault said...

You the man, Sam!

-Andy