Intro
In this guide we'll explore how to define our own keyboard shortcuts in linux for both standalone and chained commands.
Linux GUIs
Linux is a lot more modular than other OSes and this includes its Graphical User Interfaces. I am for instance using XFCE; you might be using another.
Keyboard shortcuts will most often be defined through the GUI.
If you are unsure which GUI you have, run:
sudo apt install neofetch && neofetch
Defining Keybindings for Commands
In most regularly used GUIs, it will be as simple as looking for Keyboard
under Settings
, creating a new shortcut, typing which command you want to use and assign the key combination for it. No biggie.
Defining Keybindings for Chains of Commands
If you want to chain commands, you might fall into a gotcha as they will not work.
This is because the system will execute keyboard commands through the system call and not through the shell interpreter, but this only means we'll have to make sure to invoke the interpreter before running the command.
For instance, let's suppose we want to run this command:
scrot -s /tmp/screenshot.png && xclip -selection clipboard -t image/png -i /tmp/screenshot.png && rm /tmp/screenshot.png
It will use scrot to capture a cropped screenshot to a temporary file, then use xclip to copy the file content's to the clipboard, and then it will remove the temporary file. If we assign it directly as a shortcut, nothing will happen. But we can still have a cropped-screenshot-to-clipboard shortcut.
Solution 1: Wrapping Command in a Shell Command
We can assign the shortcut to the shell command and pass the command chain we want to execute as an argument:
sh -c 'scrot -s /tmp/screenshot.png && xclip -selection clipboard -t image/png -i /tmp/screenshot.png && rm /tmp/screenshot.png'
Solution 2: Create a Script File and make it Executable
-First, create a local script:
nano ~/.local/custom-shortcut-commands/screenshot-to-clipboard.sh
Add the shebang to mark an executable script, followed by your command chain:
#!/bin/bash
scrot -s /tmp/screenshot.png && xclip -selection clipboard -t image/png -i /tmp/screenshot.png && rm /tmp/screenshot.png
Give execution permissions:
chmod +x ~/.local/custom-shortcut-commands/screenshot-to-clipboard.sh
Then, add the file location to the keybinding; (~/.local/custom-shortcut-commands/screenshot-to-clipboard.sh
in this case) since the script was flagged as an executable, the invocation of the file is enough to invoke the script.
Conclusion
Have fun customizing your Linux installation!
Top comments (2)
Use sxhkd daemon, not GUI
Once you create own config - you can use it always
didn't know about it, I'll take a look and update the article, thanks!