RaindeerKernel RaindeerKernel - 11 months ago 43
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 Source

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


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

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.)