Bash script date / time of execution

I'm trying to figure it out now and turn it off. I have a bash script environment in Linux environment which for security reasons I want to prevent execution from 9:00 to 17:00 if the flag is not specified. Therefore, if I do this. /script.sh between 9am and 5pm, he would say “NO GO”, but if I do. /script.sh -force, it bypasses the check. Basically, make sure that the person is not doing something by accident. I tried some date commands, but can't wrap this thing around me. Can anyone help?

+3
source share
4 answers

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

+3
source

The main 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 checked this (a script called "so.sh") by doing:

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

He worked in Pacific time (08:50), and not in central time (10:50). The point here is that your controls are as good as your environment variables. And users can futz with environment variables.

+2
source

It 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
+1
source

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
0
source

Source: https://habr.com/ru/post/1728651/


All Articles