Editing

Introduction

GNU Readline edits the input line in bash, psql, python, and most REPLs. This reference covers the default Emacs-style keys, history expansion, and ~/.inputrc.

Movement

KeyAction
C-aStart of line
C-eEnd of line
C-f / C-bForward / back one character
C-lRedraw the screen
C-gAbort the current command
C-dDelete char under cursor (EOF if empty)
BackspaceDelete char before cursor

These Emacs-style keys work in every prompt that links Readline, including bash, psql, and python. Arrow keys work too when the terminal sends the expected escape sequences.

See: Readline movement commands

Word motions

KeyAction
M-f / M-bForward / back one word
M-dKill forward to the end of a word
M-DELKill back to the start of a word
C-wKill back to whitespace

C-w stops only at whitespace, so it removes --flag=value whole. M-DEL stops at punctuation too.

See: Readline killing commands

Kill and yank

KeyAction
C-kKill to end of line
C-uKill to start of line
C-yPaste the last kill
M-ySwap in an earlier kill
M-.Insert the last word of the previous command

Killed text lands on the kill ring; press C-y then M-y to cycle older entries. In bash C-u is line discard, not the Emacs number prefix.

See: Readline killing commands

Undo and transpose

KeyAction
C-x C-u / C-_Undo the last edit
M-rRevert every change to this line
C-tTranspose two characters
M-tTranspose two words

Undo is remembered per history line and steps all the way back to an empty line. M-r discards the whole edit instead of one step at a time.

See: Miscellaneous commands

Numeric arguments

M-3 C-b                     # back three characters
M-2 M-d                     # kill two words forward
M-5 C-h                     # delete five characters backward

Digits and M-- build a count for the next command. C-u is the prefix in stock Emacs, but bash binds it to unix-line-discard.

See: Numeric arguments

History

KeyAction
C-rSearch backward as you type
C-sSearch forward as you type
C-r againNext older match
RETAccept the match and run the line
C-gCancel, keep the typed line
M-p / M-nNon-incremental search back / forward

C-r is the fastest way to find an earlier command: type a fragment, press C-r again to walk matches, then RET. M-p asks for a string instead of searching live.

See: Searching for commands in the history

Repeat a command

apt install ripgrep
sudo !!                     # sudo apt install ripgrep

Event designators

SyntaxExpands to
!!Previous command
!nCommand number n
!-nn commands back
!stringMost recent command starting with string
!?string?Most recent command containing string

Event designators pick the history entry to reuse; !n takes the number printed by history.

See: Event designators

Reuse arguments

cp report.txt /tmp/backup.txt
echo !^ !$                  # report.txt /tmp/backup.txt

Word designators

SyntaxExpands to
!$Last word of the previous command
!*All arguments of the previous command
!^First argument of the previous command
!:2Second word of the previous command
!:2-4Words 2 through 4

Words count from 0 at the command name; !$ is shorthand for the last word.

See: Word designators

Substitute parts

grep -r todo src
^todo^FIXME^                # repeat with todo replaced
ls /usr/local/bin
cd !$:h                     # cd /usr/local

Modifiers

SyntaxExpands to
^old^newPrevious command with old replaced
!!:pPrint the command without running it
!$:hDirectory part of the last word
!$:tFilename part of the last word

Single quotes suppress expansion, a backslash escapes !, and set +H turns it off for the session. Add :p to any designator to preview the result.

See: Modifiers

History limits

HISTCONTROL=ignorespace:ignoredups:erasedups
HISTIGNORE='ls:cd:pwd:exit:&'
HISTSIZE=10000
HISTFILESIZE=20000
shopt -s histappend

Values

SettingEffect
ignorespaceSkip lines starting with a space
ignoredupsSkip a repeat of the last line
ignorebothignorespace plus ignoredups
erasedupsRemove older copies before saving
HISTIGNOREColon-separated patterns to skip
HISTSIZEEntries kept in memory
HISTFILESIZEEntries kept in the history file
histappendAppend on exit instead of overwriting

HISTIGNORE patterns must match the whole line, and & matches the previous history line. Prefix a one-off command with a space once ignorespace is set.

See: Bash variables

Configuration

Common settings

# ~/.inputrc
set editing-mode emacs
set completion-ignore-case on
set show-all-if-ambiguous on
set enable-bracketed-paste on
set bell-style none
set history-size 10000

show-all-if-ambiguous lists completions on the first TAB. Bracketed paste inserts a pasted block as one string instead of running each character as a key. history-size caps Readline's list; in bash raise HISTSIZE too.

See: Init file syntax

Rebinding keys

"\C-x\C-r": re-read-init-file
"\e[1;5C": forward-word
"\e[A": history-search-backward

C-x C-r reloads ~/.inputrc. Binding \e[A to history-search-backward makes Up search by the prefix already typed. Keys are written \C-a (Control), \M-a (Meta), or spelled out (Control-u).

See: Readline init file

Macros

"\C-o": "> output"
"\C-g": "git status\C-m"

A macro inserts its text into the line. A trailing \C-m presses Return, so the second macro runs git status.

See: Keyboard macros

Conditionals

$include /etc/inputrc

$if Bash
  # C-x C-e opens the line in $EDITOR
  "\C-x\C-e": edit-and-execute-command
$endif

$if mode=vi
  set keymap vi-insert
  "\C-l": clear-screen
$endif

$if tests the application, the editing mode, the terminal, or the Readline version. Close each branch with $endif; $else adds an alternative. $include reads another init file.

See: Conditional init constructs

vi mode

Switching modes

Persist

set editing-mode vi

This shell

set -o vi

Esc enters command mode; i, a, I, and A return to insert mode. set -o vi changes the running shell, while the inputrc line covers new sessions.

See: Readline vi mode

Command mode

KeyAction
EscEnter command mode
h / lLeft / right
w / b / eWord forward / back / end
0 / $Start / end of line
f / tJump to a character

Esc leaves insert mode. Readline implements the POSIX sh vi subset, not full vi; motions take an operator such as d or c.

See: Readline vi mode

Editing text

KeyAction
i / aInsert before / after cursor
I / AInsert at start / end of line
xDelete the character
dd / dwDelete line / word
cw / ccChange word / line
p / PPaste after / before
uUndo

i and a return to insert mode. An operator plus a motion edits a range, so d$ deletes to the end of the line.

See: Readline vi mode

Searching

KeyAction
/ / ?Search the history
n / NNext / previous match

Searches walk the command history; n repeats the match and N reverses the direction.

See: Readline vi mode

Keymaps

inputrc

set keymap vi-insert
"\C-l": clear-screen

bind

bind -m vi-insert '"\C-l": clear-screen'

Keymaps keep vi insert and command bindings apart: vi-insert, vi-command, emacs-standard, emacs-ctlx. bind -m changes one without an inputrc edit.

See: Keymaps

Tools

Bash bind

bind -P                      # current function bindings
bind -l                      # every Readline function name
bind -q kill-word            # keys bound to one function
bind -v                      # current variable values
bind -s                      # macros

Shell commands

bind -x '"\C-x\C-w": git status'
bind -m vi-insert '"\C-l": clear-screen'

bind -x runs a shell command; the buffer is in READLINE_LINE and the cursor in READLINE_POINT. bind -m keymap scopes a binding to one keymap.

See: Bash builtins: bind

Python

import readline

readline.parse_and_bind("set editing-mode vi")
readline.parse_and_bind('"\\C-l": clear-screen')

name = input("Name: ")

Importing readline makes input() use Readline, so the keys on this sheet apply. parse_and_bind takes the same syntax as ~/.inputrc.

See: Python readline

See also

0 Comments for this cheatsheet. Write yours!