Command History

bash lets you display or modify previous commands. This is similar to the C shell’s history mechanism. Commands in the history list can be modified using:

  • Line-edit mode

  • The fc command

In addition, the command substitutions described in Chapter 8, also work in bash.

Line-Edit Mode

Line-edit mode lets you emulate many features of the vi or Emacs editors. The history list is treated like a file. When the editor is invoked, you type editing keystrokes to move to the command line you want to execute. Arrow keys work on most terminals in both Emacs mode and vi command mode. You also can change the line before executing it. See Table 7.23 for some examples of common line-edit commands. When you’re ready to issue the command, press Return.

The default line-edit mode is Emacs. To enable vi mode, enter:

$ set -o vi

Note that vi starts in input mode; to type a vi command, press Esc first.

The mode you use for editing bash commands is an entirely separate choice from the editor that is invoked for you automatically within many commands (for instance, the editor mail readers invoke when you ask them to create a new mail message). To change the default editor, set the VISUAL or EDITOR variable to the filename or full pathname of your favorite editor:

$ export EDITOR=emacs

Table 7-23. Common Editing Keystrokes

vi Emacs Result
k Ctrl-P Get previous command.
j Ctrl-N Get next command.
/ string Ctrl-R string Get previous command containing string.
h Ctrl-B Move back one character. ...

Get Linux in a Nutshell, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.