I am new in programing with bash script. Here is my problem: I am going to open a sort of data whose file name includes the date (format: file_yyyymmddhh.nc). There are some requirements:

  • mm is from 01 to 12. This must be a two-digit integer.

  • dd is from 01 to 28, 30, or 31, depending on the what month it is.

I tried to solve the problem with if structure and loops. I know that I could use something like this so that I can apply ${dd} to my filename.

if [${mm} == 01] ; then 
  for ((i=1; i<=31; i=i+1))

But I don't know how to specify ${dd} to be a 2-digit integer especially when ${dd} <= 9. Is there any way to fix the code above?

  • @arzyfex I am going to open a list of files and the file name is formatted as 'yyyymmdd'
    – Wayne Tsai
    Commented May 17, 2016 at 16:41

1 Answer 1


You can use printf to format your numbers. Here the %02d denotes a two digit integer with leading zeros if appropriate.

dd=$(printf "%02d" $i)

You can extend this so that if $y, $m, $d, and $h contain your year, month, day, and hour numbers the construct could become this

file=$(printf "file_%04d%02d%02d%02d.nc" $y $m $d $h)

While we're here, your construct ${dd}=i is incorrect. The $ symbol is prefixed in front of a variable name to get that variable's value (in your case, i is the variable and $i equates to its value). So in your case you would instead have written dd=$i.

  • It works! And thanks for pointing out what I did wrong:)
    – Wayne Tsai
    Commented May 22, 2016 at 6:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .