简体   繁体   中英

bash script execution date/time

I'm trying to figure this out on and off for some time now. I have a bash script in Linux environment that, for safety reasons, I want to prevent from being executed say between 9am and 5pm unless a flag is given. So if I do ./script.sh between 9am and 5pm it would say "NO GO", but if I do ./script.sh -force it would bypass the check. Basically making sure the person doesn't do something by accident. I've tried some date commands, but can't wrap that thing around my mind. Could anyone help out?

Write a function. Use date +"%k" to get the current hour, and (( )) to compare it.

Basic answer:

case "$1" in
(-force)
    : OK;;
(*)
    case $(date +'%H') in
    (09|1[0-6]) 
        echo "Cannot run between 09:00 and 17:00" 1>&2
        exit 1;;
    esac;;
esac

Note that I tested this (a script called 'so.sh') by running:

TZ=US/Pacific sh so.sh
TZ=US/Central sh so.sh

It worked in Pacific time (08:50) and not in Central time (10:50). The point about this is emphasizing that your controls are only as good as your environment variables. And users can futz with environment variables.

This works

#!/bin/bash

# Ensure environmental variable runprogram=yes isn't set before 
unset runprogram 

# logic works out to don't run if between 9 and 5pm as you requested
[ $(date "+%k")  -le 9 -a  $(date +"%k")  -ge 17 ] && runprogram=yes  

# Adding - avoids the need to test if the length of $1 is zero
[ "${$1}-" = "-forced-" ] && runprogram=yes 

if [ "${runprogram}-" = "yes-" ]; then 
    run_program 
else 
    echo "No Go" 1>&2 #redirects message to standard error
fi

Test script:

#!/bin/bash

HOUR=$(date +%k)
echo "Now hour is $HOUR"

if [[ $HOUR -gt 9 ]] ; then
  echo 'after 9'
fi


if [[ $HOUR -lt 23 ]]; then
  echo 'before 11 pm'
fi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM