Sleep until a specific time/date

前端 未结 18 2141
栀梦
栀梦 2020-11-28 21:13

I want my bash script to sleep until a specific time. So, I want a command like \"sleep\" which takes no interval but an end time and sleeps until then.

The \"at\"-d

18条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 21:20

    timeToWait = $(( $end - $start ))

    Beware that "timeToWait" could be a negative number! (for example, if you specify to sleep until "15:57" and now it's "15:58"). So you have to check it to avoid strange message errors:

    #!/bin/bash
    set -o nounset
    
    ### // Sleep until some date/time. 
    # // Example: sleepuntil 15:57; kdialog --msgbox "Backup needs to be done."
    
    
    error() {
      echo "$@" >&2
      exit 1;
    }
    
    NAME_PROGRAM=$(basename "$0")
    
    if [[ $# != 1 ]]; then
         error "ERROR: program \"$NAME_PROGRAM\" needs 1 parameter and it has received: $#." 
    fi
    
    
    current=$(date +%s.%N)
    target=$(date -d "$1" +%s.%N)
    
    seconds=$(echo "scale=9; $target - $current" | bc)
    
    signchar=${seconds:0:1}
    if [ "$signchar" = "-" ]; then
         error "You need to specify in a different way the moment in which this program has to finish, probably indicating the day and the hour like in this example: $NAME_PROGRAM \"2009/12/30 10:57\"."
    fi
    
    sleep "$seconds"
    
    # // End of file
    

提交回复
热议问题