I need to write an infinite loop that stops when any key is pressed.
Unfortunately this one loops only when a key is pressed.
Ideas please?
#!/bin/bash
count=0
while : ; do
# dummy action
echo -n "$a "
let "a+=1"
# detect any key press
read -n 1 keypress
echo $keypress
done
echo "Thanks for using this script."
exit 0
Here is another solution. It works for any key pressed, including space, enter, arrows, etc.
Tested in bash:
Usually I don't mind breaking a bash infinite loop with a simple CTRL-C. This is the traditional way for terminating a
tail -f
for instance.You need to put the standard input in non-blocking mode. Here is an example that works:
Edit 2014/12/09: Add the
-icrnl
flag tostty
to properly catch the Return key, usecat -v
instead ofread
in order to catch Space.It is possible that
cat
reads more than one character if it is fed data fast enough; if not the desired behaviour, replacecat -v
withdd bs=1 count=1 status=none | cat -v
.read
has a timeout parameter-t
which could be used. Do a non blocking check for input, seeing if the return status is 0 and if so break from the loop.