RaindeerKernel RaindeerKernel - 2 months ago 11
Bash Question

How can I allow a shell script to be paused during execution?

Let's say I have a script which acts as an alarm. Say you set it for five minutes and it does the following:

printf '%s\n' 'Alarm set for 5 minutes'
sleep 300 && printf '%s\n' 'Alarm!'


How can I implement a way to continuously monitor for a pause key, say "p" or "SPC", then wait until a key is pressed again to resume normal execution of the script? I want a way for the user to pause the alarm.

Edit: To clarify, I want to continuously monitor for a pause key while running other code. This is as opposed to stopping execution to listen on stin.

Answer

This can be done easily if you accept sending a signal as the method to abort the timer:

#!/bin/sh

printf '%s\n' 'Alarm set for 5 minutes.  ^C to continue'
sleep 300 &
trap : INT
if wait; then
    echo Timer complete
else
    echo Timer aborted
fi

Note that this implementation does not actually stop the sleep process, and if that process is doing something more significant, you will probably want to terminate it. (Instead of doing nothing in the trap, send a signal to the child.)