i want while loop syntax in UNIX for date 2018-03-28 to 2018-04-02
-
2See: stackoverflow.com/questions/28226229/bash-looping-through-dates which I found with a google search for "bash looping dates". I'm unclear what you mean by UNIX. "can you please help me" tends to annoy people because it makes them think "why should I help you".Att Righ– Att Righ2018-05-22 14:13:29 +00:00Commented May 22, 2018 at 14:13
Add a comment
|
1 Answer
Edited to use YYYYMMDD output format rather than YYYY-MM-DD format, according to user's wishes in comments, and add start date and end date variables, also taken from comments.
Assuming GNU date:
startdate='2018-03-28'
enddate='2018-04-02'
enddate=$( date -d "$enddate" +%Y%m%d ) # rewrite in YYYYMMDD format
i=0
while [ "$thedate" != "$enddate" ]; do
thedate=$( date -d "$startdate + $i days" +%Y%m%d ) # get $i days forward
printf 'The date is "%s"\n' "$thedate"
i=$(( i + 1 ))
done
Alternatively:
startdate='2018-03-28'
enddate='2018-04-02'
enddate=$( date -d "$enddate + 1 day" +%Y%m%d ) # rewrite in YYYYMMDD format
# and take last iteration into account
thedate=$( date -d "$startdate" +%Y%m%d )
while [ "$thedate" != "$enddate" ]; do
printf 'The date is "%s"\n' "$thedate"
thedate=$( date -d "$thedate + 1 days" +%Y%m%d ) # increment by one day
done
Output:
The date is "20180328"
The date is "20180329"
The date is "20180330"
The date is "20180331"
The date is "20180401"
The date is "20180402"
-
can you help me on remove the - form date i want to be print date like 20180328 in this formatsunil– sunil2018-05-22 15:49:02 +00:00Commented May 22, 2018 at 15:49
-
@sunil Use
%Y%m%dinstead of%F.2018-05-22 15:50:12 +00:00Commented May 22, 2018 at 15:50 -
then output is going to infinite.. can you help me to remove - while print and write a input in other file –Kusalanandasunil– sunil2018-05-22 16:43:28 +00:00Commented May 22, 2018 at 16:43
-
@sunil if you change the date format, you will need to change the string that it is tested against in the inequality correspondinglysteeldriver– steeldriver2018-05-22 16:55:16 +00:00Commented May 22, 2018 at 16:55
-
i have one more doubt :- while im using below code its going to infinite, please help me :- #!/bin/bash i=0 thedate="2018-03-28" enddate="2018-04-02" while [ "$thedate" != "$enddate" ]; do thedate=$( date -d "$thedate + $i days" +%F ) new_date=$( date -d "$thedate " +%Y%m%d ) printf 'The date is "%s"\n' "$new_date" i=$(( i + 1 )) done and output should be The date is "20180328" The date is "20180329" The date is "20180330" The date is "20180331" The date is "20180401" The date is "20180402"sunil– sunil2018-05-22 17:10:24 +00:00Commented May 22, 2018 at 17:10