I'm trying to figure out the best way to halt a running script using a keyboard shortcut while the terminal is not the active window.
This led me to learn about watching keyboard events with cat /dev/input/eventX ( where X is a number that corresponds to keystroke events)
I then learned about a tool evtest that will run until interrupted printing out the events (keystrokes) as they occur in a human readable format.
Here is the script I've managed so far, but its not working as expected. In a perfect solution the user could press Key_Space at anytime to halt the script, but I don't think that's possible here. So my workaround is to give them a 2 second window at the begining of the loop.
#!/bin/bash
exitCase='*type 1 (EV_KEY), code 57 (KEY_SPACE)*'
while [ true ] do
evtest /dev/input/eventX | read -s -t 2 line
if [ "$line" = "$exitCase" ]
then
echo caught event
exit 0
else
echo loop doing stuff
fi
done
Problem is the script will run once without looping, is there a better way to do this? Or how can I adjust my script to loop until it sees input matching the exit case?
I think another potential problem is that a single keystroke will print out multiple lines so maybe i need a evtest /dev/input/eventX | while read line? But after trying I could only get it to loop on events, and not while waiting for them.