Linux – Keyboard shortcuts in the virtual terminal

keyboard shortcutslinuxterminaltty

Is there any way of configuring keyboard shortcuts in the Linux virtual console?

For example, if I go to tty1 then press the key combination Ctrl+Alt+H, I would like the script /usr/bin/hello.sh to be executed.


Ideally, the shortcut would be available even before logging in (in which case it would be executed with the privileges of a user that I specify). I don't mind modifying the kernel either, if that's the only way of accomplishing this. Also, it doesn't have to be a shell script, it can also be a normal ELF binary or even a kernel module making system calls.


Example use cases

  1. I'm in the console and browsing the web with something like links and I want to turn down the screen brightness. I press Fn+End, which happens to be the brightness down key and produces a single keycode, and a program runs which reduces the brightness by writing something in a /sys file.
  2. I'm in a console text editor and listening to some music in the background that's being played by mpd. I press the (play/pause) key, which again produces a single keycode, and that has the effect of executing a program which sends a signal to mpd to pause the current song.

Solution

Following dirkt's idea of using /dev/input, I created evd (event daemon) for this purpose. The application can be started in the background and will take over the keyboard wherever you are, including before login and within X.

Best Answer

Partial answer (because it's just an outline, and untested):

Write a demon which listens to whatever /dev/input device corresponds to your main keyboard (there are symlinks, look at them). Start that demon as the user you specify, using whatever init system you have (systemd, sysv, whatever).

The demon processes key events as defined in input-events-codes.h (or look at the source code of evtest). It has a state machine that recognizes your desired key sequences, and spawns whatever process you specify when such a sequence is complete.

This should be available before you login, and will always execute as the same user, no matter what user you are logged in at the virtual console. It will also execute under X, again as the same user.


Alternative, if you want to execute something in a shell: Use tmux or a similar program which can bind key sequences to actions. I suppose it should also be possible to automatically start tmux and attach to a new session whenever you log in at a virtual console, but I haven't looked into that.

This won't work before log in, but will also work in graphical terminal emulators that have keyboard focus, and will execute the script as the user which is logged in.

Related Question