If Statement to Kill Program at User Set Time - Bash

138 views Asked by At

wrote a script that accepts user input for time and is supposed to kill a program when the current time is equal to the time the user input.

it's broken down to:

read -p "Enter when your class ends in the format 00:00 " endclass
echo "We will close your meeting at $endclass"


NOW=$(date +"%H:%M")
while True
do
  echo "Waiting for class to end..."
  if [ $NOW = $endclass ]
  then
    pkill Chrome
  fi
done

put the if statement inside a while loop to continue executing the script until the current time reaches the desired time.

I am able to run the script without any errors but it does not kill Chrome at all.

any tips?

1

There are 1 answers

0
soith On

There are couple of problems with the while-loop:

  • the main problem is that the NOW variable is not updated inside the loop
  • the check only needs to happen (at most) every second; so a sleep 1 inside the loop would prevent it from taking up CPU resources (add from flooding stdout with the echo'd message).

Perhaps an alternative to a while-loop would be to add a sleep for the precise number of seconds, for example:

echo "Waiting for class to end..."

# Determine how many seconds to the endclass time:
#   1. Have the date command finish the seconds-based arithmetic expression
#   2. Then, sleep for the bash-shell evaluated number of seconds from the expression
endclass_h="${endclass%%:*}"
endclass_m="${endclass##*:}"

sleep $(( endclass_h*3600 + endclass_m*60 - $(date +"%H*3600 - (10#%M*60 + 10#%S)") ))

pkill Chrome