1

I need to create a while loop that continuously loops until a key press is registered, specifically the 'q' key for quit.

Here's my (failed) attempt:

while [ -z "$QUIT" ]
do
    <Script stuff>
done &
read -sn 1 QUIT
export QUIT

However the while loop doesn't exit / end if I press any key. This is because $QUIT seems to only be accessible 'forwards' from where it is set, not backwards to the parent while loop section. Is there a way around this, or an alternative method for allowing my while loop to exit when a key (q if possible) is pressed?

Cheers.

Ajjy. K F
  • 11
  • 2
  • Read never is reaching. If you want to do that create a file with the pid to stop the process. –  Oct 29 '18 at 22:37
  • If you launch the script with & and export QUIT=1 . It works. –  Oct 29 '18 at 22:40
  • Thanks. Is there not a possible way to do it just in 1 file though, for simplicity's sake? – Ajjy. K F Oct 29 '18 at 23:10
  • You could do something similar https://unix.stackexchange.com/questions/235626/how-to-bind-commands-like-ctrlc-to-one-key-for-example-f5 –  Oct 29 '18 at 23:15
  • Your idea was that https://stackoverflow.com/q/24016046/9799449 –  Oct 29 '18 at 23:17

2 Answers2

0

I did it like this:

while true
do
    # Suck in characters until we timeout, collecting sequence
    seq=
    while IFS= read -s -n1 -t 0.01 key; do
        [ "$key" = "" ] && key=" "
        seq="${seq}${key}"
    done

    # Do whatever processing for seq

done
Jack
  • 5,801
  • 1
  • 15
  • 20
0

Here's an example showing how to kill a background job

while true
do
    echo "hello"
    sleep 1
done &

while read -sn 1 QUIT && [[ $QUIT != 'q' ]];
do
    echo "QUIT $QUIT"
done

# This kills the background job
kill %1
ssemilla
  • 3,900
  • 12
  • 28