Bind function keys to the bash
During a recent Linux basics training session one of the students asked how to assign F-keys or function keys on the keyboard to bash commands. Despite my decades of Linux usage, I never even considered this. So I went on to figure it out and learned how to do it.
Two ways do the trick. Either make an entry to the inputrc
file or use the bind
command. Both ways work and both have their advantages.
Using the bind
command
An easy way to test the function key integration is to use the bind
command. The only difficulty may be the way to enter the key codes.
First, look at this example:
bind '"^[OP":"ls -l^M"'
Assuming that you're using bash
to execute this command the way to construct this command works a little different than just copy and paste it. If you where to just copy and paste the string above it will likely NOT work.
Instead construct your command like this first:
bind '"":"ls -l"'
Then navigate to the first pair of quotes and pres Ctrl-v
. Now press the desired function key. The key code will be added automatically. The command should look like this now:
bind '"^[OP":"ls -l"'
If your key code looks different to this example, don't worry. It depends on your OS and maybe on your keyboard.
Finally go to the end of your command which you put into the second pair of quotes. Press Ctrl-v
again and press the enter key leading to a command like this:
bind '"^[OP":"ls -l^M"'
This complete example would bind my F1 key to the command ls -l
followed by an enter. If the enter is not added the key would only write the command but not execute it.
As with many other bash related configuration elements the bind is only active within your bash session and will be reset once you end it.
To make it permanent you can add it to your .bashrc
. Using vim
seems to be the easiest way. Use it just like you would to it in the bash with the Ctrl-v
key combination and everything. Just don't copy and paste as it won't work.
Using inputrc
Another way to set the shortcut is to add it to your /etc/inputrc
or your local ~/.inputrc
file. It works similar to the bind command. I used vim
to add it to a local .inputrc
file like this:
"^[OP": "ls -l^M"
Again, I used
vim
withCtrl-v
to enter the key codes.
If I'd make this global or if I had a complete .inputrc
file this would be my preference. However, if this is the only line in a local ~/.inputrc
file all the global shortcuts won't work anymore. You could of course add the contents of /etc/inputrc
to the local file but I don't like copies like that.