Searching Ones Command History

There are two ways one can search their command history.

METHOD 1…

One can use the Bash reverse-incremental search function, <Ctrl>-<R>, to search in reverse through shell history. This useful if you remember typing a command line with “bar” in it and you wish to rerun the command without retyping it. Type <Ctrl>-<R> and the text bar. The last command you typed containing “bar” will appear on the input line.

Like the Emacs command of the same name this is called an incremental search because it builds the search string in character increments as one types. Typing the string “cat” will search for and display the last input line containing a “c“, then “ca” and at last “cat” as one types the individual characters of the search string. Typing  <Ctrl>-<R> again retrieves the next previous command line that matches the string.



Examples…
Put the last command entered containing the string “grep” back on the command line…
$ <Ctrl>-<R>
(reverse-i-search)`’: grep

Put the third-to-last command entered containing the string “grep” back on the input line…
$ <Ctrl>-<R>
(reverse-i-search)`’: grep
<Ctrl>-<R> <Ctrl>-<R>

Observe that when the command is displayed on the input line one simply has to press <Enter> to run it. And one can edit the input line as if it were the command line.

METHOD 2…

One can also pipe shell history through grep to output lines that match a pattern. This puts nothing on the command line but returns all the matches at once. One might also want to pipe this output to a pager such as less so they can scroll through it.

Example…
Peruse lines of one’s command history containing the text “foobar“…
$ history | grep foobar | less <Enter>

This entry was posted in BSD, Bash, GNU/Linux, UNIX and tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>