How to Create Keybinds Using the bind Command in Linux

How to Create Keybinds Using the bind Command in Linux

Creating a keyboard shortcut in Bash means assigning a key sequence to an action at the prompt. Bash’s bind builtin connects that sequence to an editing function, inserted text, or a shell command through Readline, the line editor used at an interactive prompt.

In this piece, I’ll show how to test a key binding at the prompt and save it for future sessions.

TL;DR

Bash’s bind builtin assigns a key sequence to a Readline editing function, inserted text, or a shell command.

  • Inspect a function with bind -q name, and inspect the full function map with bind -P.
  • Use ~/.inputrc for Readline settings or ~/.bashrc for Bash-specific interactive setup.
  • Try a custom shortcut at a prompt before saving it. Another application or the terminal may consume the key first.

What Is the bind Command in Bash?

bind is a Bash builtin that changes how GNU Readline handles keys while editing a command line. Readline is the line editor Bash uses at an interactive prompt.

The keyword also appears in Linux networking, device-tree documentation, mount options, and DNS. Those topics use different mechanisms, so this tutorial focuses on Bash Readline.

Binding kindEffectExample task
Readline functionRuns a named editing actionMove the cursor by a word
MacroTypes characters into the current command lineInsert a repeated option
Shell command (-x)Runs a Bash command when the key is pressedCall a helper command from the prompt

Choose a Readline function for editing, a macro for literal text, and -x when the action must run as a shell command. An alias is different because it expands a command name rather than responding to a key sequence. See this LinuxForDevices guide to Linux aliases for that alternative.

How to Create a Bash Key Binding Step by Step

A reliable binding starts with inspection, uses a key sequence that does not disrupt a common action, and gets tested in the prompt where it will be used.

Step 1: Check an existing Readline function

Run bind -q with a function name to ask which sequences call it. The recorded query for backward-word returned these mappings:

bash bind_probe.sh
backward-word can be invoked via "\e\e[D", "\e[1;3D", "\e[1;5D", "\e[5D", "\eb".
bind_probe.sh: line 3: bind: warning: line editing not enabled
bind_probe.sh: line 3: bind: `definitely_not_a_readline_function': unknown function name
Bash lists backward-word sequences and reports an unknown Readline function
The query lists mappings, while the deliberately invalid name produces an error.

The warning and error came from asking a noninteractive child shell to use line editing. A script can inspect mappings. The prompt reveals how the key behaves.

Step 2: Select a key sequence and editing action

Readline notation uses \C- for Control and \M- for Meta. Escape sequences often represent keys such as arrows, but the sequence can vary by terminal.

This example maps Control plus Left Arrow’s common sequence to backward-word for the current Bash session:

bind '"\e[1;5D": backward-word'

Ask Readline to display the sequences for the function after assigning it:

bind -q backward-word

Use bind -P for function-to-key listings, bind -p for output formatted for reuse, and bind -l to list function names. Use the prompt test to confirm the terminal sends the sequence you expected.

Step 3: Insert text or run a shell command

A macro adds text to the editable command line. For example, Control-G can insert a help option that you then append to a command:

bind '"\C-g":"--help"'

To execute a shell command on a key press, use -x and quote the complete key-to-command expression as one argument:

bind -x '"\C-g":printf "shortcut pressed\\n"'

These two examples assign the same key, so use one at a time or choose distinct sequences. Bash exposes READLINE_LINE and READLINE_POINT to a command run through -x, allowing a command to read or change the current line and cursor position. Use bind -X to inspect shell-command bindings separately from Readline function mappings.

Step 4: Save the binding for future sessions

Use ~/.inputrc for Readline configuration shared by programs that use Readline. Put the binding there without the Bash bind command:

"\e[1;5D": backward-word

To load an input file into the current Bash session, use bind -f ~/.inputrc. For Bash-only setup, place a bind command in ~/.bashrc, which interactive non-login Bash shells normally read. Login-shell startup can follow a different path, so check the Bash startup files guide if a new terminal does not apply the setting.

Separate Readline entries from shell commands so each file uses the syntax its reader expects.

Step 5: Remove or revise a binding

Use bind -r keyseq to remove one sequence, and bind -u function to remove all sequences assigned to a named function. I compared the backward-word query before and after removing an unrelated sequence in a child shell. Its five reported mappings remained.

bind -r '\C-x\C-e'
bind -q backward-word

If several keys invoke the same action, removing one leaves the other mappings intact. Test an unfamiliar removal in a temporary shell.

Step 6: Verify the key at the prompt

After a query confirms the mapping, type a harmless unfinished command and press the chosen shortcut. For backward-word, enter two words and check that the cursor moves to the start of the preceding word. Pressing a macro key should insert its characters without executing the line.

For an -x binding, use a harmless command first and confirm its behavior before attaching a command that changes files or depends on the current directory. Exit the test prompt without submitting an unfinished line if its contents are not meant to run.

How the bind syntax is read

A binding expression has a key sequence on the left and an action on the right, separated by a colon. The outer shell quotes keep the expression together as one argument. Readline interprets escape notation such as \C-g inside it.

With a named function, the right side is the exact Readline function name. With a macro, the right side is text placed in the command buffer. The function edits the line, while macro characters may become part of a command when you press Enter.

The GNU Bash syntax accepts key sequences containing more than one key. A sequence with a shared prefix can make Readline wait briefly for another character before deciding which binding matched. If that delay appears, inspect nearby sequences and choose combinations that do not overlap with shortcuts you use often.

Keymaps provide another scope. Bash supports Emacs-style and Vi-style editing maps. The -m option targets a chosen map.

Readline entries and Bash commands use different configuration syntax. Put a key-sequence entry in an input file and a bind command in Bash configuration. Mixing the forms can cause a parse error or leave the mapping unapplied.

The lowercase and uppercase listing options also serve distinct purposes. Lowercase output such as -p and -s is formatted for reuse, while -P and -S display current mappings. Copy a relevant entry rather than replacing the entire configuration with a default listing.

GoalUseful formWhat to inspect
Find an editing functionbind -lAvailable Readline function names
See current editing mappingsbind -PFunction and assigned sequence
See macro mappingsbind -SKey sequence and inserted text
See shell-command mappingsbind -XCommands invoked by keys
Load Readline entriesbind -f fileFile syntax and current shell result

The listing switches answer different questions. Start with the smallest one that matches the action you configured rather than searching a complete key dump. This also helps identify whether a shortcut was set as a function, a macro, or a shell command.

A configuration file only helps after the right program reads it. If a Readline entry is valid but missing from the prompt, load the file in the current Bash session with the file option, then query the function again. If it appears after that but vanishes in a new terminal, investigate startup-file selection rather than changing the key notation.

For a startup command, keep the line in the file Bash actually reads for that session. A noninteractive shell may skip interactive configuration, and login shells can follow a different startup sequence. The Bash documentation describes those startup rules, while the site’s startup-file guide gives a practical overview.

Edge Cases and Fixes

When a shortcut does not work, first determine whether Bash received the key and whether the configuration was loaded in the shell you are using.

SymptomLikely reasonWhat to check
unknown function nameReadline does not recognize the function nameUse bind -l to find available names and check spelling.
Warning that line editing is not enabledThe command ran outside an interactive editing sessionUse the query for inspection, then test the key at an interactive Bash prompt.
Shortcut does nothing or inserts unexpected charactersThe terminal sent a different sequence, or another mapping conflictsCheck the terminal’s key sequence and inspect with bind -P or bind -q.
Binding disappears in another terminalThe setting was entered only in the current shellSave it to the appropriate input or Bash startup file and check how Bash starts.
Key works in Bash but not an editorThe editor manages its own input and shortcut settingsConfigure that application separately. Readline settings apply to Readline clients.

Terminal drivers can handle some control characters before Readline sees them, and a foreground program can read keystrokes while it owns the terminal. Test after returning to the shell prompt and use a key combination not claimed by the terminal or application.

The Bash builtin’s version follows the Bash version, rather than a separate Linux package version for bind. Check the shell with bash --version. The Linux shells guide describes how shell behavior differs beyond Bash.

A script can print a line-editing warning because it has no interactive prompt. Apply the configuration in the Bash session that should receive the shortcut.

For a failed query or assignment, check the command status and the spelling of the function or key sequence. An error from a query means the requested function name was not accepted. A successful listing only describes the configuration Bash currently has loaded, so it cannot confirm which bytes a particular terminal sends when a key is pressed.

The function and macro listings are useful when documenting a setup, while shell-command listings help audit actions that may run immediately. Keep an old mapping nearby before replacing it. To restore a removed function mapping, use its original sequence and function name from the listing or a known-good configuration file.

When a shortcut is meant to run a command, consider what state the command assumes. A key press does not make a command safer or verify its arguments. Prefer a harmless helper, leave destructive actions behind an explicit confirmation, and avoid using a key that can be pressed accidentally while entering another command.

Control and Meta notation describe input as Readline receives it, rather than as a printed label on a keyboard. A terminal may encode an arrow as a multi-character escape sequence, and another terminal can send a different sequence for what looks like the same key.

Compare the function query before and after the change. Inspect macro mappings with the macro listing. Use the shell-command listing for a command action.

A command binding also runs in the shell context where you press it. That means the current directory, shell variables, and command availability can affect its result. A script path that works from one directory may fail from another, so use a stable path or make the action independent of the current directory.

Keep the first experiment reversible. A temporary binding lasts only in the current shell, and a new shell gives you a clean place to test persistent configuration. Save the change only after confirming its key sequence, action type, and target keymap.

Conclusion

Use Bash bind to assign an intentional key sequence, then test it at the prompt and save it in the matching configuration file.

The GNU Bash manual’s bind entry documents builtin options, while the Readline initialization syntax reference explains configuration notation. The LinuxForDevices man command guide covers reading local manuals, and the shell script guide helps when an -x action should invoke a script.

FAQ

These answers clarify what Bash’s binding controls and where its settings apply.

How do I check the bind version in Linux?

There is no separate version for the Bash bind builtin. Run bash --version to check Bash, which provides the builtin and interactive Readline support.

Does Bash bind a network port?

No. Bash bind configures Readline key sequences. Network port binding uses the socket bind() system call and is a different task.

Does mount --bind copy files?

No. mount --bind makes an existing directory available at another mount point; it is unrelated to Bash keyboard bindings.

Where should I save a Bash key binding?

Use ~/.inputrc for Readline configuration or ~/.bashrc for Bash-specific interactive setup. Bash startup behavior depends on whether the shell is interactive and login-enabled.