In most shells, it’s possible to bind a command to a key (or series of keys). This should not be confused with an alias, which lets us define a shortcut command. Let’s look at aliases first, then key bindings.
Aliases
We’ll use a git
command to demonstrate aliases, but the same principle applies to any command. If you work with git
much, you’re probably used to issuing the git status
command to see which files have been modified in the repository you’re working in:
$ git status On branch master Your branch is up-to-date with 'origin/master'. Untracked files: (use "git add <file>..." to include in what will be committed) testrt.py todo.txt nothing added to commit but untracked files present (use "git add" to track)
We can make that simpler by defining an alias:
$ alias gits="git status" $ gits On branch master Your branch is up-to-date with 'origin/master'. Untracked files: [...]
Here, we alias gits
to the git status
command, and now typing gits
followed by return has the same effect as typing the command in full.
Bind Keys
When we bind a key or keys to a command, simply typing those keys will run the command. There are lots of options, but we’ll keep it very simple here. Let’s bind Alt-Return
to the git status
command:
bind -x '"\e\r": git status'
Step by step:
bind
is abash
built-in command-x
defines this as a shell command binding (as opposed to a function name or readline command)- The single quote enclosing the rest of the command prevents command substitution within it
"\e\r"
is an escape sequence where\e
is the escape key and\r
is return. WhenAlt-Return
is typed, the key sequence generated isEscape Return
.- The colon terminates the key sequence
git status
is the shell command to bind to the key sequence
Now, typing ESCAPE
followed by return
will run the git status
command. You can also type Alt-Return
, which will generate the same key sequence.
So now when you’re working with git
, a simple Alt-Return
will show the status of the repository.
Scratching the Surface
There’s a lot more that can be done with key bindings, and maybe we’ll revisit them in a future Linux Tips article.
Was This Linux Tip Useful?
Let us know in the comment below.
This is a nice tip but for a newbie might be slightly confusing, since the reference:
“\e\r” is an escape sequence where \e is the escape key and \r is return.
comes after first stating that you are demonstrating an Alt+Return binding. Before saying that it will ‘also’ work with with the Alt key, you ask the user to test it with Escape+Return.
My pedantry might be cranked up to 11 on this one!
Thanks, Lee. I’ve added a short explanation to hopefully make that clearer.