1

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.

thornjad
  • 155
  • 1
  • 13
  • 1
    Possible duplicate of [Press enter or wait 10 seconds to continue](http://stackoverflow.com/questions/9483633/press-enter-or-wait-10-seconds-to-continue) – Marc B Sep 16 '16 at 15:54
  • This is not a duplicate of that particular question, since there is not invocation or `read` here. – William Pursell Sep 16 '16 at 17:02

3 Answers3

1

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

William Pursell
  • 204,365
  • 48
  • 270
  • 300
0

Many shells have a builtin read function that allows you to read from stdin. You can use this to make your program interactive.

However, if you need to do this kind of I/O etc., I think you should shift away from shell to a real programming language.

Noufal Ibrahim
  • 71,383
  • 13
  • 135
  • 169
0

you can do like below

// alarm running = true
while true
do
   //running  running is true resume or start alarm
   /** pseudo code
       if running == true
           start or resume alarm
       else 
           pause alarm
       your alarm start or re
    **/
  IFS= read -r -t 0.5 -n 1 -s holder && var="$holder"
  if [ "$var" == "p" ]
    then
          #running = false
         echo "You have pause your alarm "
  elif [ "$var" == "R" ]
   then
      #running = true
     echo "start your timer"
   fi
done
William Pursell
  • 204,365
  • 48
  • 270
  • 300
Md Ayub Ali Sarker
  • 10,795
  • 4
  • 24
  • 19