Bash – do some infinite job while waiting for specific key pressed – possible?

I have the following infinite loop in bash, executing do_some_simple_job every 10 minutes:

while true
do

    do_some_simple_job

    sleep 600

done

I would like for the script to accept some key presses while doing this job, like for canceling the job, but not terminating script, is that even possible?

Answer

Yes, this is possible.

#!/bin/sh

sigint_handler () {
    echo "Killing the job ($job_pid)"
    kill $job_pid
}

while true; do
    some_simple_job & job_pid=$!
    trap 'sigint_handler' INT

    echo "Job started ($job_pid)"

    wait
    trap - INT

    echo "Job finished, waiting 10 minutes..."

    sleep 600
done

This sh script (also works in bash, ksh93 and other compatible shells) contains your infinite loop. After launching the job in the background, it installs a signal handler, a small routine that should be run whenever the script catches a particular signal. The signal that it catches is the INT (interrupt) signal, which you send by pressing Ctrl+C.

The script waits for the job to finish, then it sleeps for 10 minutes (as your script does). Before it sleeps, it uninstalls the signal handler so that you may interrupt the script with Ctrl+C.

If an INT signal comes in while the job is running, the signal handler will kill the job using its process ID. The script will then progress to uninstall the handler and sleep.

If you don’t exit the script during the 10 minutes of sleep, the loop continues with launching the job and installing the handler again.

Leave a Reply

Your email address will not be published. Required fields are marked *