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:
.bashrc1
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 | 473 docker ps |
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 | $ !474 |
A few things to keep in mind:
- The search is only for your current terminal session, this might be shared across different tabs in some terminal programs
- Your history can be deleted if you close the terminal program, reboot, buy a new machine
- The grep search does not work for multi-part commands
- 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.