Time condition loop in shell

后端 未结 8 1565
故里飘歌
故里飘歌 2020-12-04 10:34

I have just started learning shell script recently, so I don\'t know much about it.

I am trying to find example of time based while loop but not having any luck.

8条回答
  •  眼角桃花
    2020-12-04 10:50

    You can explore the -d option of date.

    Below is a shell script snippet to exemplify. It is similar to other answers, but may be more useful in different scenarios.

    # set -e to exit if the time provided by argument 1 is not valid for date.
    # The variable stop_date will store the seconds since 1970-01-01 00:00:00
    # UTC, according to the date specified by -d "$1".
    set -e
    stop_date=$(date -d "$1" "+%s")
    set +e
    
    echo -e "Starting at $(date)"
    echo -e "Finishing at $(date -d "$1")"
    
    # Repeat the loop while the current date is less than stop_date
    while [ $(date "+%s") -lt ${stop_date} ]; do
    
        # your commands that will run until stop_date
    
    done
    

    You can then call the script in the many different ways date understands:

    $ ./the_script.sh "1 hour 4 minutes 3 seconds"
    Starting at Fri Jun  2 10:50:28 BRT 2017
    Finishing at Fri Jun  2 11:54:31 BRT 2017
    
    $ ./the_script.sh "tomorrow 8:00am"
    Starting at Fri Jun  2 10:50:39 BRT 2017
    Finishing at Sat Jun  3 08:00:00 BRT 2017
    
    $ ./the_script.sh "monday 8:00am"
    Starting at Fri Jun  2 10:51:25 BRT 2017
    Finishing at Mon Jun  5 08:00:00 BRT 2017
    

提交回复
热议问题