I'm looking for a way to create a Bash script that can detect every individual keystroke, including not just regular keys but also modifier keys like Alt, Ctrl, and Shift. I understand that keys like the arrow keys produce ANSI escape codes in the Linux console or GNOME Terminal, which I can access in raw read mode. But can a Bash script handle modifier keys and detect when they're pressed individually? Is there a method to reopen the terminal or modify it to achieve this?
5 Answers
In general, it's a no-go for capturing individual Alt, Ctrl, or Shift keystrokes across all setups. For specific environments like a Linux console or X11, there are methods, but SSH just doesn't allow for it.
The answer depends a lot on what you mean by "keystrokes". If you're after every character immediately when it's pressed, check out the `stty` command to adjust the terminal settings. But if you want detailed key events (like keycodes), that really relies on your OS and hardware setup. For instance, if you're using a serial console or SSH, that info may not even exist since those connections typically don't transmit key events, just character data.
That's interesting! When I SSH and use tmux, I can access those control keys. Like CTRL-B followed by arrow keys for resizing panes. So there must be a way to send those from a terminal environment to a remote session.
While Bash isn’t specifically designed for this, you can employ commands like `read -rsn1` to read single characters or keys. For control or escape sequences, some additional coding is necessary to parse those. However, take care with the timeout parameters and how you handle keys to ensure your script behaves as expected.
Interesting! I’ve worked on a library for handling ANSI escape codes in the terminal. Have you ever tried pushing ANSI codes back to the terminal to request cursor positions?
If you're using X11, there are ways to get access to that data, and Bash can use it. But if you're running outside of X, like in a serial console or SSH session, you might not be able to detect those modifier keys at all since the device might not send that data. Also, bear in mind that if you're working through SSH, detecting modifier keys like Alt or Ctrl isn't feasible because that data simply isn't transmitted.
Would it even be possible under Wayland without a specific exposed hook? Wayland restricts low-level input access due to security concerns, which X11 doesn't.
If you need comprehensive keystroke handling, maybe consider writing a small C program instead of sticking strictly to Bash. There are libraries to handle Linux keyboard events which could give you a more robust option for detecting all key actions.
I see what you mean. But aren't there already keyloggers that do this? Maybe it's worth looking into those solutions.

Right, I get that. I mainly need to send function keys and arrow keys during an SSH session.