How to loop through dates using Bash?

后端 未结 8 715
一整个雨季
一整个雨季 2020-12-02 06:22

I have such bash script:

array=( \'2015-01-01\', \'2015-01-02\' )

for i in \"${array[@]}\"
do
    python /home/user/executeJobs.py {i} &> /home/user/         


        
相关标签:
8条回答
  • 2020-12-02 06:50

    I had the same issue and I tried some of the above answers, maybe they are ok, but none of those answers fixed on what I was trying to do, using macOS.

    I was trying to iterate over dates in the past, and the following is what worked for me:

    #!/bin/bash
    
    # Get the machine date
    newDate=$(date '+%m-%d-%y')
    
    # Set a counter variable
    counter=1 
    
    # Increase the counter to get back in time
    while [ "$newDate" != 06-01-18 ]; do
      echo $newDate
      newDate=$(date -v -${counter}d '+%m-%d-%y')
      counter=$((counter + 1))
    done
    

    Hope it helps.

    0 讨论(0)
  • 2020-12-02 06:53

    Brace expansion:

    for i in 2015-01-{01..31} …
    

    More:

    for i in 2015-02-{01..28} 2015-{04,06,09,11}-{01..30} 2015-{01,03,05,07,08,10,12}-{01..31} …
    

    Proof:

    $ echo 2015-02-{01..28} 2015-{04,06,09,11}-{01..30} 2015-{01,03,05,07,08,10,12}-{01..31} | wc -w
     365
    

    Compact/nested:

    $ echo 2015-{02-{01..28},{04,06,09,11}-{01..30},{01,03,05,07,08,10,12}-{01..31}} | wc -w
     365
    

    Ordered, if it matters:

    $ x=( $(printf '%s\n' 2015-{02-{01..28},{04,06,09,11}-{01..30},{01,03,05,07,08,10,12}-{01..31}} | sort) )
    $ echo "${#x[@]}"
    365
    

    Since it's unordered, you can just tack leap years on:

    $ echo {2015..2030}-{02-{01..28},{04,06,09,11}-{01..30},{01,03,05,07,08,10,12}-{01..31}} {2016..2028..4}-02-29 | wc -w
    5844
    
    0 讨论(0)
提交回复
热议问题