How to pad integers with zeros in BASH

When a parameter study is generated, the case directories can be named with strings that contain “0000x”. When a subset of such directories is required, it is useful to write for loops in bash that pad a number with zeros.

Step-by-step guide

This code snippet loops over a sub-set of OpenFOAM simulation directories and fetches the last line in the OpenFOAM logfile (slurm*.out on a cluster with the SLURM workload manager), delivering the total computational time:

?> for i in 2 5 8 11; do tail -n 1  timingCPU_$(printf "%05d" $i)_voFoam-hex-shear2D/slurm*; done
ClockTime = 20 s
ClockTime = 86 s
ClockTime = 392 s
ClockTime = 1741 s

Padding of a value in a variable is done with the printf command:

?> for i in 2 4 6 8; do echo prefix-$(printf "%04d" $i)-suffix; done

See also