Article | TIL, you can use function keys as bash shortcuts

TIL, you can use function keys as bash shortcuts

You can assign a function key in bash to type text into your terminal. I’m not talking about snippet expansion that will work everywhere, this is just a bash feature. I really like it, as it works over SSH, and can be setup when I provision my development machine with Ansible (a future blog post perhaps!).

Here is the magic:

# f10 does git add
bind '"\e[21~":"git add -A; git status\n'

# f11 does git commit
bind '"\e[23~":"git commit --verbose\n"'

# f12 does git push
bind '"\e[24~":"git push; git status\n'

A breakdown of the magic:

  • bind bind a key sequence to a macro.

  • \e The escape key.

  • [21~ A sequence following an esc represents a key on the keyboard. In this case, f10.

  • \n A newline character. Think of it as hitting return at the end of the line.

Very useful. In fact, I use f9 to start a simple HTTP server so I can view code coverage over an SSH connection. Check out how to start an HTTP server in one line here.

To find which character sequence you need, in your terminal hit ctrl-v then the key. It will print out something that looks like this: ^[[21~. The ^[ stands for the escape key, but it can also be represented as \e, which I find more readable when deciphering scripts I wrote months ago. Different terminal emulators can output different sequences for same key, so if you have unexpected behaviour on a new terminal, double check the sequence.

Message sent
Message could not be sent
|