History and readline shortcuts

Beginner · 7 min

Search and reuse past commands with Ctrl-R, !! and !$, edit the line with readline keys, and tune HISTCONTROL so your history stays useful. Tested in Bash 5.3.

Before thisVariables and the environmentQuoting - single, double and escapes

Will Brock · 7 min

History and readline shortcuts

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Will BrockReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Bash keeps a numbered list of the commands you typed. Ctrl-R searches it as you type, and history lists it.
  • History expansion reuses pieces: !! is the last command, !$ its last word, !* all its arguments, !n line n, !abc the last command starting with abc, and ^old^new^ repeats it with a substitution.
  • Line editing comes from the readline library: Ctrl-A and Ctrl-E move to the ends, Ctrl-W deletes a word, Ctrl-U deletes to the start, Ctrl-Y pastes it back, Alt-. inserts the last argument.
  • HISTSIZE caps the in-memory list and HISTFILESIZE the file. HISTCONTROL=ignorespace:erasedups keeps secrets typed with a leading space out of the list and removes duplicates.
  • History expansion only happens in interactive shells. In a script !! is just a command that does not exist.

Why history exists

Most of what you type at a prompt is a slight variation on something you typed before: the same command with another filename, the same long pipeline with a changed pattern. Retyping it is slow, and the cost is not only time. Every retype is a chance for a typo.

So Bash keeps a numbered list of your commands and gives you two tools: a way to find old ones, and a way to edit the line you are building. The second comes from a library called readline, which many programs share, so these keys work in more places than Bash. Everything below I ran in a real interactive Bash 5.3 session on macOS.

Listing and repeating

$ echo one
$ echo two
$ echo three
$ history
    1  echo one
    2  echo two
    3  echo three
    4  history

History expansion starts with ! and is expanded before the command runs. Bash prints the expanded line first, so you can see what it will do:

$ !!
history
...
$ !2
echo two
two
$ !echo
echo two
two

!! is the previous command, !2 is line 2, !echo is the most recent command that began with echo. Words from the previous command have their own handles:

$ echo hello world
hello world
$ echo !$
echo world
world
$ echo foo bar
foo bar
$ echo !*
echo foo bar
foo bar

!$ is the last word and !* is everything after the command name. The classic use is mkdir /srv/app/logs followed by cd !$. And ^foo^FOO^ reruns the previous command with a substitution:

$ ^foo^FOO^
echo FOO bar
FOO bar

Because this runs before your command, a stray ! in an interactive double-quoted string can surprise you, since double quotes do not stop history expansion. Single quotes do: echo "again: !!" printed again: echo first in my test, while echo 'again: !!' printed it literally. See the quoting lesson.

History expansion is switched off for scripts. When I put echo hi then !! in a script file:

hi
p45.sh: line 2: !!: command not found

Searching with Ctrl-R

Ctrl-R is the key to learn first. Press it and type part of any earlier command. Bash searches backwards as you type:

(reverse-i-search)`hello': echo hello world

Press Enter to run it, Right-arrow or Ctrl-E to edit it first, Ctrl-R again for the next older match, and Ctrl-G to give up. I typed hello, pressed Enter, and echo hello world ran again.

Editing the line

readline has a second set of shortcuts for the line you are typing. I tried the ones that matter:

  • Ctrl-W deletes the word before the cursor. Typing echo one two three then Ctrl-W twice and Enter ran echo one.
  • Ctrl-U deletes from the cursor back to the start of the line, and Ctrl-Y pastes the last thing you deleted. With echo typed after C-u followed by Ctrl-Y, the text I had just erased (echo drop me) came back in the new line.
  • Ctrl-A and Ctrl-E jump to the start and end. Typing world, Ctrl-A, then echo hello gave echo hello world.
  • Alt-. inserts the last argument of the previous command, and repeated presses walk back through earlier ones. On macOS Terminal the Alt (Option) key needs “Use Option as Meta key” turned on.
  • Ctrl-T swaps the two characters around the cursor: abcdef with the cursor before ef became abcedf.

You can ask Bash what a function is bound to, for example bind -q reverse-search-history answers "\C-r", and bind -q yank-last-arg answers "\e.". Ctrl-W is also set in the terminal driver (stty -a shows werase = ^W), so it works even where readline does not.

Tuning the list

$ echo "HISTSIZE=$HISTSIZE HISTFILESIZE=$HISTFILESIZE HISTCONTROL=${HISTCONTROL-unset}"
HISTSIZE=500 HISTFILESIZE=500 HISTCONTROL=unset

HISTSIZE is how many lines stay in memory and HISTFILESIZE how many the file keeps. These were the defaults in my scratch session, with no startup file. HISTCONTROL controls what gets recorded:

$ HISTCONTROL=ignorespace:erasedups
$  secret-looking command ignored        # leading space
$ echo one
$ echo one
$ history | tail -3
   13  HISTCONTROL=ignorespace:erasedups
   14  echo one
   15  history | tail -3

The space-prefixed line ran (it failed, since it is not a command) but was not recorded, and erasedups removed the earlier echo one. The space trick is a convenience, not a safeguard: it only affects the history list, not what a process listing or a logging shell would show.

The file is written when the shell exits. After typing two commands and exit, my HISTFILE held echo first, echo second and exit. Those settings belong in a startup file, as covered in the startup files lesson.

About the video

“Mastering Bash History & Ctrl+R: Boost Your Command Line Efficiency” is a 7-minute video from Will Brock, published September 2024. The description says it covers Ctrl-R search, storing a large number of commands in the history file, avoiding duplicates and sharing history between sessions. I could not read a transcript, and the page has no chapters. It is an English-language channel. The video centres on history and Ctrl-R. For the editing keys, You Suck at Programming’s short readline video is linked as a second view.

Where this fits

You can reuse and edit what you type. The next step is making the shell shorter for the things you type every day: aliases and functions in rc files.

Check yourself

  1. 01You typed mkdir /srv/app/logs and now want to cd into that directory. What is the shortest way?

    cd !$ expands to cd /srv/app/logs, because !$ is the last word of the previous command. Alt-. does the same thing while you can still edit the line.

  2. 02You ran a long command with the typo 'grep -r fooo .'. How do you rerun it corrected?

    Type ^fooo^foo^ to repeat the previous command with the first fooo replaced by foo.

  3. 03How do you keep a command containing a token out of your history?

    With HISTCONTROL=ignorespace (or ignoreboth) set, start the command with a space. The line runs but is never recorded.

  4. 04Why does a script that contains !! fail with 'command not found'?

    History expansion is an interactive feature and is off in non-interactive shells, so !! is read as a command name.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark