Q:

Shell: print a number with preceding zeros to a variable?

I want to print numbers in a bash script using the following C format : %05d.
So I have two variables
$num1
$num2

And when I set for example num1=12 I would like to have echo $num2 equals to 00012. 
How to do that ?

A:

num1=12
printf -v num2 '%05d' "$num1"

Note that this sets num2 only once. If you want num2 to always reflect the current value of num1, you need to define it as a function:
num2() { printf '%05d' "$num1"; }

...and then call it as such:
num2

