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.
$line
ought to be empty here, so it doesn't look like thethen
branch can ever run, so if the loop stops it's because of the part you've elided in the else branch (if there is something there in reality). You may want to [edit] in any relevant parts of that branch, and/or any debugging you've done to try to figure out what's running and what isn't. – Michael Homer Sep 02 '19 at 03:49while
statement (missing;
beforedo
). – Kusalananda Sep 02 '19 at 06:13