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?
CodePudding user response:
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 "d" $year)
for ((month=${date_start:4:2}; month<=${date_end:4:2}; month ))
do
mm=$(printf "d" $month)
for ((day=${date_start:6:2}; day<=${date_end:6:2}; day ))
do
dd=$(printf "d" $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)
CodePudding user response:
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