Mar 14, 2005
Tip: History Search in Bash
If:
- you find yourself typing the same long command in the shell repeatedly, or
- you want to recall some command that you have executed yesterday, or
- you don’t remember the exact options you recently used but you know the command or parts of the command line,
then you might be interested in this.
The Bash shell has some built-in functions that can be bound to keys, including functions to search the command line history. By default the reverse-search-history function is bound to Ctrl-r, and the contra forward-search-history to Ctrl-s. This is an incremental search, and mostly useful if you remember only the middle bits of a command line. There are two others: non-incremental-reverse-search-history (bound to Meta-p by default; Meta could be Alt or Esc) and non-incremental-forward-search-history (Meta-n). All four of them do not let you go to the next match if there are multiple matches, only the first match is shown, so you need to use the most unique part of the command line to get the one you want.
The most useful functions, at least for me, are actually not bound to any keys by default, which is a shame. They are history-search-forward and history-search-backward. I use them a lot. So the first thing I do (after changing password) when I got a new account with a bash shell is to add these lines to $HOME/.inputrc (unless it’s overriden with the env var $INPUTRC) and re-login:
"\C-f": history-search-backward
"\C-g": history-search-forward
Using these two functions I can type the first few letters of the command I have previously run, then I keep pressing Ctrl-f until I find the command that I want, and Ctrl-g to go back to the opposite search direction.
By the way, you can always use alias to create a shorthand for a long command. And everyone uses the Tab button regularly, right? You’d be insane not to do that anyway.
Follow
ctrl-s stops screen scroll in bash. ctrl-q to restore.
Hmm, this is what bash(1) man page says (reformatted for clarity):
Actually I knew about Ctrl-s, but I wasn’t aware when I wrote this post since I was looking at the man page. Maybe the system’s inputrc or gnome terminal override Ctrl-s here.