Enabling Search in the Terminal

07-06-2020


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

1
2
3
...
alias gh='history | grep'
...

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

1
$ gh docker

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

1
2
3
4
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.

1
2
3
$ !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.