Bash History Navigation

Elijah Manor 3 days
464 words 3 min read
There are better ways to navigate history, but I find myself doing this exact same behavior at times. Better alternatives include using control-r to search history, or if you use ohmyzsh you can partially type and then use the up-arrow to cycle through partial matchesupupupAlmostthere...❯ clear❯ git status❯ code .❯ npm run dev❯ npm tFound it!<enter>upelijahmanor.comManorisms - A Story of Bash History Navigation@elijahmanorNot yetupNodaNopeupupCloseup

If you'd like to download the above comic there's a JPG version. You can also find more developer comics like this from the comics page.

Bash History

As you interact with bash or zsh shell your commands are being stored in a history file (either .bash_history or .zsh_history). You can access your history by typing the history command, but be warned, the results will probably be very long! You might want to pipe the results through less or grep to somehow page or limit the results.

One fun thing you can do is to run the following command to sort and deduplicate the history entries and give the count of your top 5 commands!

history | awk '{print $2}' | sort | uniq -c | sort -rn | head -5

4315 git
1219 npm
 561 yarn
 470 z
 339 code

NOTE: I don't recall where I first found the above shell command, but doing a quick Google search found a very similar command from Arturo Herrero's (@ArturoHerrero) command-line-one-liners repository.

Bash Navigation

Being able to look into your shell history is handy, but being able to navigate to previous commands is even more useful. There are a few ways that I regularly browse my bash history.

Up Arrow

As the comic above suggests, clicking up-arrow key will navigate to the last command in your history. If you continue to click the up-arrow you will continue to get more commands that are older from your history. This can be very useful, but if you have a lot of items in your history it can be time consuming.


Thankfully, there is another mechanism and that is ctrl + r. If you press the ctrl and r keys together you'll be set in a special mode where you can search for a command from within your history. As you type you'll see a command that partially matches what you typed. You can press ctrl + r again to find the next match from history that matches your search term or you can tweak your search term for finer control. Once you find the command you like, you can press enter to execute it or press ctrl + c to exit out of the search.

OhMyZsh Up Arrow

If you use ohmyzsh, it provides another mechanism that is nice. It combines the idea of the Up Arrow that we explained above, but here you can start to type a command and then press up-arrow and it'll complete the command with the closest starts-with match. You can continue to press up-arrow to navigate back in history for matches to that sub-string.