Search code examples
bashdateterminal

Getting first and last days of each month, starting with current date


I want to run a python file multiple times and change input values every time it's run. The input values, in this case, is a website address and two date spans with a given start date and a given end date.

Example:

I want to loop through and run this file with different dates up to 12 months back.

The file

Iteration 1, todays date and the first date of the current month:

run -i 'file.py' 'https://www.example.com/' '2019-09-01' '2019-09-12'

Iteration 2, the first date of last month and the last date of last month:

run -i 'file.py' 'https://www.example.com/' '2019-08-01' '2019-08-31'

Iteration 3:

run -i 'file.py' 'https://www.example.com/' '2019-07-01' '2019-07-31'

...

Keep on iterating 12 months back

I've already managed to build a for loop that generates the dates but i'm having troubles to incorporate the python file.

for i in {1..12}; do 
    echo $(date -I -d "2019-09-01 -$i months")
done

Output:

2019-08-01
2019-07-01
2019-06-01
2019-05-01
2019-04-01
2019-03-01
2019-02-01
2019-01-01
2018-12-01
2018-11-01
2018-10-01
2018-09-01

Solution

  • You could use the code below:

    d1=$(date '+%Y-%m-01')
    d2=$(date '+%Y-%m-%d')
    for i in {1..12}; do 
        run -i 'file.py' 'https://www.example.com/' $d1 $d2
        d2=$(date -d "$d1 -1 day"  '+%Y-%m-%d')
        d1=$(date -d "$d2" '+%Y-%m-01')
    done
    

    Explanation:

    • we begin with the first day as d1 and the current one of the current month as d2.
    • for each iteration, we deduce d2 from the previous date d1, which is the first day of the previous month, by subtracting one day.

    The following command lines will be executed:

    run -i file.py 'https://www.example.com/' 2019-09-01 2019-09-12
    run -i file.py 'https://www.example.com/' 2019-08-01 2019-08-31
    run -i file.py 'https://www.example.com/' 2019-07-01 2019-07-31
    run -i file.py 'https://www.example.com/' 2019-06-01 2019-06-30
    run -i file.py 'https://www.example.com/' 2019-05-01 2019-05-31
    run -i file.py 'https://www.example.com/' 2019-04-01 2019-04-30
    run -i file.py 'https://www.example.com/' 2019-03-01 2019-03-31
    run -i file.py 'https://www.example.com/' 2019-02-01 2019-02-28
    run -i file.py 'https://www.example.com/' 2019-01-01 2019-01-31
    run -i file.py 'https://www.example.com/' 2018-12-01 2018-12-31
    run -i file.py 'https://www.example.com/' 2018-11-01 2018-11-30
    run -i file.py 'https://www.example.com/' 2018-10-01 2018-10-31