I have the following script which spams a button in a program when the V button is pressed

winid=$(xdotool search "application name here" | head -n1)
while true; do
read -rsn1 input
if [ "$input" = "v" ]; then
    xdotool keydown --window $winid "button"
    xdotool keyup --window $winid "button"

However, this only works when the the terminal is focused, is there any way to make it listen to all key presses?

  • Could you please tell us what your ultimate goal is? Whatever you're trying to do (and how you're trying to do) is really weird to me. – egmont Oct 2 '16 at 9:53
  • I would use it for a number of programs. Mostly games though, for example mGBA, to spam through pressing A. (It's quite tiring, actually) – MightyAlex200 Oct 2 '16 at 15:11
  • Sorry, I totally don't get it. Care to explain the entire story from the beginning to the end, please? – egmont Oct 2 '16 at 18:53
  • I play pokemon on a GBA emulator. This lets me speed up the game, however I still need to press "X" as fast as possible to actually do anything. I would like a script that presses X as fast as possible for me (but only when I am holding the B button down). – MightyAlex200 Oct 3 '16 at 14:57
  • OK I see :) One possibility that occurs to me right now is to use xbindkeys or something similar instead of a shell script and its "read" statement – as it was already recommended to you by someone else. – egmont Oct 3 '16 at 18:21

This works for the root user:

cat /dev/input/$(grep -E  'Handlers|EV=' /proc/bus/input/devices | \
                 grep -B1 'EV=120013' |  grep -Eo 'event[0-9]+') | \
while read -rsn1 foo ; do echo "$foo" ; done | nl

Output (until Ctrl-C):

     1  ԥ
     2  �W
     3  ^

The code reads from whichever /dev/input/event* file currently corresponds to the keyboard. Echos each keypress on separate lines, then numbers each line -- keypresses accumulate quickly, so the line numbers help show the routine is working.

Try opening a text editor in a small foreground window, enter some text in the editor, and notice the numbers scroll by on the background terminal.

The grep code above borrowed from JacobP's answer here: Linux keyboard event capturing /dev/inputX

  • okay thx, but is there any way to actually detect if I pressed a certain button and then execute a command? – MightyAlex200 Oct 2 '16 at 14:28
  • 2
    @MightyAlex200 Yes, use a tool designed for this purpose, such as xbindkeys. Your script is not at all useful for this. – Gilles Oct 2 '16 at 19:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.