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:
bindis abashbuilt-in command-xdefines 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\eis the escape key and\ris return. WhenAlt-Returnis typed, the key sequence generated isEscape Return.- The colon terminates the key sequence
git statusis 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.


