Detecting keyboard state in shell

A discussion happened recently and a need was raised to detect key states (whether a certain key is pressed) in shell, see here (second comment). So I went googling for a while, found the answer here: and tidy it up a little bit, as attached.

Usage: kbstate key [devpath]
Returns: 0 if key is pressed, 1 otherwise, 255 for errors.

key is either lshift, rshift, lalt, ralt, lctrl, or rctrl (that's left/right shifts, left/right alts, left/right controls) in English keyboard, not sure the equivalents in others. If you hack the source you can easily check for other keys too.

devpath is the path to the Linux's keyboard event device. The default value is /dev/input/by-path/platform-i8042-serio-0-event-kbd (that is, the built-in PS/2 keyboard) but most of the time you would specify /dev/input/event5 or something. Scan /proc/bus/input/devices, find a device whose handlers is "kbd", and you know which /dev/input/eventXXX you need to specify.
If you need to test multiple keyboards (PS/2, USB, etc) you will need to call kbstate multiple times, one for each devpath.

Get the source, 32-bit static binary and 64-bit static binary.

Posted on 16 May 2013, 23:20 - Categories: Linux
Edit - Delete

No comments posted yet.

Add Comment

Show Smilies
Security Code 6959018
Mascot of Fatdog64
Password (to protect your identity)