Searching command history with Ctrl-r
From UnixCasts.com (formerly Learning the UNIX command line on OS X)
In our last newsletter, The bang operator, I demonstrated how we can easily run previous commands from our shell history. This shortcut is a huge time saver and also prevents you from typing commands repeatedly, which in turn means less wear and tear on your fingers. However, I have found that one downside to using the bang operator is that I rarely remember the exact commands that I've typed out in a specific shell, which is only made more complicated if I have several shell sessions open, as when I am using a tool such as tmux. As a result, I end up running the history
command frequently, inspecting its verbose output which takes additional time.
As an alternative, we can use Ctrl-r, a shell keystroke combination which allows us to quickly search through our command history. To use it, just type the Control key at the same time as you type the letter r, then start typing out the beginning of a command and watch it offer a match from your shell history. If the match isn't exactly what you need, you can continue to type the Ctrl-r keystroke combination to continue searching back through your command history. Once you've found the command you want to execute, just tap the Enter key.
I've found that by using this shell feature, I rarely need to manually list my previous typed commands using the history
command. Keep in mind though that the number of commands that Ctrl-r can search through is based on the HISTSIZE
, which under bash can be set inside.bash_profile
:
# Setting history to 1 million commands
HISTSIZE=1000000
Similarly, in zsh you can set this environment variable inside .zshrc
.
Want more UNIX tips? Please check out UnixCasts.com.