Enabling Search in the Terminal

Jul 6, 2020 min read

If you use the terminal, even a little bit, you will likely need to reuse past commands. Usually this means pressing the up arrow a bunch of times until you find what you need. Here is a handy setup to allow you to “search” past commands and pick the necessary command from a list. Simply we’re going to use grep to search through the terminal’s history for matching commands. Grep is command-line tool for searching plain text.

Here’s the setup:

Create a Bash alias to search your terminal’s history:

.bashrc

...
alias gh='history | grep'
...

Search for a word from your command, in part or in full:

$ gh docker

This should return a set of results from your current terminal session’s history that match your search term:

  473  docker ps
  474  docker run -it --rm -p 8080:8080 -v /var/run/docker.sock:/var/run/docker.sock -v $(pwd):/api -w="/api" node bash
  475  docker stop 808
  476  docker stop 5a3

The number beside the command is basically the id of that line in your terminal history, if you want to re-run that command, you can simply enter a ! in front of the number and press enter. If you want to modify the command slightly (there’s probably another way) I will simply run the command, then quickly cancel, modify, and then run the command.

$ !474
docker run -it --rm -p 8080:8080 -v /var/run/docker.sock:/var/run/docker.sock -v $(pwd):/api -w="/api" node bash
root@da4e92f543ec:/api#

A few things to keep in mind:

  1. The search is only for your current terminal session, this might be shared across different tabs in some terminal programs
  2. Your history can be deleted if you close the terminal program, reboot, buy a new machine
  3. The grep search does not work for multi-part commands
  4. The search does not allow for fuzzy search

This setup works really well for me and finding even a close enough version of a command without having to scroll endlessly or retype a command in the terminal.