Ubuntu – Bash shell scripting: how to detect Alt+N keystroke

bashcommand linescriptsshortcut-keys

I want to write a script that always listens in the background and executes a particular command when the user hits a specific key combination such as Alt + N. How this can be done?

Best Answer

Download the following python module: showkey.py

Then create a python script (let's call it test.py):

#!/usr/bin/env python

from showkey import ShowKey

def alt_n(arg):
    print "Alt N was pressed"

sk = ShowKey()
sk.addKeyAction([49, 56], alt_n)    # adds handler for Alt-N comb.
sk.run()

Put showkey.py in your PYTHONPATH or put both test.py and showkey.py in the same folder.

Run your python script this way:

sudo ./test.py

The alt_n() callback will be triggered when the user hits the Alt + N combination. Adapt the handler content for your needs.

To know the keycodes (the same codes used by the showkey command) to use with showkey.py, just run it as a script again with sudo. All keypress events will be printed in your terminal.

$ sudo ./showkey.py 
Current terminal mode: OFF
Key pressed - keycode: 28
Key pressed - keycode: 56
[...]
Related Question