0

I want to loop using limits extracted from two variables, and get the loop variable have a specific number format, e.g.=001 instead of just 1.

How can I do that?

Ferny
  • 46
  • 4

2 Answers2

0

The following code does it:

date_start=20160701
date_end=20160731

for ((year=${date_start:0:4}; year<=${date_end:0:4}; year++))
do
  yyyy=$(printf "%04d" $year)
  for ((month=${date_start:4:2}; month<=${date_end:4:2}; month++))
  do
    mm=$(printf "%02d" $month)
    for ((day=${date_start:6:2}; day<=${date_end:6:2}; day++))
    do
      dd=$(printf "%02d" $day)

      echo ${yyyy}${mm}${dd}

    done
  done
done

My question: is there a better way to do this inside a Bash script? If yes, why that way is better?

(Linux Ubuntu 20.04.03, Bash 5.1.16)

Ferny
  • 46
  • 4
0

If you want to iterate through a range of dates (represented as YYYYMMDD) and you have GNU date, then this may be what you want:

#!/bin/bash

date_start=20160701
date_end=20160731

for ((cur_date = date_start; cur_date <= date_end;)); do
    echo "$cur_date"
    cur_date=$(date -d "$cur_date next day" +%Y%m%d)
done
M. Nejat Aydin
  • 9,597
  • 1
  • 7
  • 17
  • @Nejat, of course, sorry for that. Your solution is indeed much better to loop through the days. My question pointed to the format of the numbers for year, month, and day. Inside the loop you propose I get these like: `yyyy=$(printf "%04d" "${cur_date:0:4}") mm=$(printf "%02d" "${cur_date:4:2}") dd=$(printf "%02d" "${cur_date:6:2}")` It works, although for 08 and 09 I get error: `... printf: 08: invalid octal number` Why is this? – Ferny Aug 10 '22 at 22:55
  • @Ferny, an answer to that in [here](https://stackoverflow.com/a/8078505/19077548) – Ferny Aug 12 '22 at 10:15