We're an ISO27001:2013 Certified Supplier

blog-post-featured-image

We’ve discussed command line history before, with a post that shows how to ensure that multiple simultaneous shell sessions use the same history file, and how to keep commands out of the history. In this post, we look at how to search the history file.

Saving For The Future

The first thing is to ensure that sufficient commands are retained by the shell. There are two environment variables that control this, HISTFILESIZE and HISTSIZE, and they are a source of some confusion.

  • HISTSIZE determines the maximum number of commands that are held in memory for the current shell.
  • HISTFILESIZE determines the maximum number commands that are stored in the history file on disk, and are thus persistent between shell sessions.

The history file is truncated, if necessary, to HISTFILESIZE number of commands both at shell invocation and when the history file is written to disk. If HISTFILESIZE is not set, the shell sets it to the value of HISTSIZE.

The simple answer is to set HISTSIZE only. Setting it to zero will cause no history to be saved, while setting it to a negative value will cause all history to be saved. A positive number, of course, will cause that number of commands to be saved.

Searching The Past

One way of searching history is by typing ^R to the shell prompt. Whatever is typed next will be interactively searched for in the history, and the most recent matching command will be shown. Hitting return will (re-)execute that command. If the command that is auto-completed from history is the wrong one, another ^R will search back for the next match.

Another history search can be bound to (for example) the Page Up and Page Down keys, and requires the following to be in /etc/inputrc:

# map "page up" and "page down" to search the history
"\e[5~": history-search-backward
"\e[6~": history-search-forward

If you now type the start of a previous command and press Page Up, the shell will auto-complete with the last command that started with the string typed. Pressing Page Up again will search back for the next match.

Don’t overlook the other way of searching history: grep. Can’t remember how to tag a git commit, but know you’ve done it before?

$ grep ^git ~/.bash_history | grep tag
git tag 2017120500 
git push origin --tags

Was This TechTip Useful?

Let us know in the comments below.