History (command)

From LQWiki
Jump to: navigation, search

The C shell, csh, and bash (not sh) enable a feature that records all the commands you have entered and allows you to re-execute them.

Without command-line editing, this becomes a useful method to save reentering a long command without having to retype it.


If you type history at the prompt, all commands that were previously entered will be shown.

Using grep with history will enable you to look for commands previously entered with certain names, for example

 history | grep perl

will show you all the Perl scripts that you have run.

With each history entry is a number. You can reexecute the corresponding command by entering an exclamation mark, and then the number beside the command. For example, if history had

  108  vi
  109  hack
  110  history

as the last three commands, entering


at the command prompt would re-execute the command hack.



will reexecute the last entered command.

Extra features

Say for example you had given the command

$ man gethostbynam
man: no entry for gethostbynam in the manual.

You had missed out the e, and instead of reentering the command, you can instead say

$ !!e

The !! expands as the last command, and the e completes the proper name for the command.

Furthermore, say you had entered

$ telnet western-database-server

though you really meant to telnet to the eastern-disk-server. You can then do the following

$ !!:s/western-database/eastern-disk/

which performs a very simple (ie, no regular expressions) textual substitution on the previous (or the n-th command if you use !n) command.