Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash script execution date/time

Tags:

date

linux

bash

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?

like image 806
Daniil Avatar asked Dec 05 '25 10:12

Daniil


2 Answers

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

like image 112
Ignacio Vazquez-Abrams Avatar answered Dec 06 '25 22:12

Ignacio Vazquez-Abrams


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.

like image 41
Jonathan Leffler Avatar answered Dec 06 '25 23:12

Jonathan Leffler