-4

i want while loop syntax in UNIX for date 2018-03-28 to 2018-04-02

1

1 Answer 1

5

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"
6
  • can you help me on remove the - form date i want to be print date like 20180328 in this format Commented May 22, 2018 at 15:49
  • @sunil Use %Y%m%d instead of %F. Commented 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 –Kusalananda Commented 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 correspondingly Commented 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" Commented May 22, 2018 at 17:10

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.