Searching command history with Ctrl-r
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 command out 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 sessions 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 excecute, 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
.
"LEARNING THE UNIX COMMAND LINE ON OS X" SCREENCAST
If you're new to UNIX or would like to move beyond a beginner's level,
please take a look at a screencast I have produced called, “Learning the
UNIX command line on OS X”, which contains over 50 lectures and 3.5
hours of content.
As appreciation for my newsletter subscribers, I am offering a discount
on the screencast during the holiday season. Normally a $99 value,
through November 28, it's available for $29 by using coupon code
blackfriday2014. After that date
the price will go up, so please purchase your copy now to receive the
discount.
Happy Holidays!
Chip Castle