6

At times when I do CtrlR to search through command history, I find that I don't reach the entry I was looking for, even though I know it's in history. I think this is due to me having passed the entry, forcing me to use another command to go the other direction. Is there a command that allows the whole of history to be searched by looping through it (restarting the cycle) when it reaches the end?

5
  • So it should loop from first to last rather than stopping at the first?
    – Mikel
    Feb 7, 2011 at 20:39
  • @mikel Yeah, that's right.
    – tshepang
    Feb 7, 2011 at 20:40
  • 1
    Perhaps you need a better way to search. Maybe just running history | grep <something> then running !<number> would be a way of doing it?
    – Mikel
    Feb 7, 2011 at 20:42
  • @mik That's quite a bit to type :(
    – tshepang
    Feb 7, 2011 at 20:44
  • 1
    So make an alias or function for it. ;-)
    – Mikel
    Feb 7, 2011 at 20:56

1 Answer 1

9

You could use Alt+> to go back to the end of your history then search again, but maybe you knew that, and it's not what you want.

Unfortunately, I don't think there's a way to make it wrap around.

I can't see anything about it in man bash or man readline.

We could try writing a readline macro, but there's no variable telling us what line of history we're on.

So short of that, here's some other suggestions that you might find viable alternatives:


If your terminal is configured to send Ctrl+S, (e.g. by running stty stop undef), then you can change directions just by pressing it Ctrl+S.


You could use history | grep <whatever> then type !<number from left column> to run it.

If that's too long to type, make it a function to save some typing, e.g.

hgrep() {
    history | grep "$@"
}

Set up history-search-backward and history-search-forward. They can be easier to use.

e.g. ls Alt+P, Alt+P , Alt+P will search backwards thru all your ls commands.

Plus you can change directions just by pressing the other shortcut, e.g. if you're at the oldest command, you can just switch from pressing Alt+P to pressing Alt+N.

Set it up by putting this in your /etc/inputrc or .inputrc for bash:

$if mode=emacs
"\ep": history-search-backward
"\en": history-search-forward
$endif

and this in your .zshrc for zsh:

bindkey -M emacs '^[p' history-beginning-search-backward
bindkey -M emacs '^[n' history-beginning-search-forward

You could even go one step further and make the Up arrow do this.


Finally, are you sure the command is being entered into history? Maybe it's being ignored due to the HISTCONTROL or HISTIGNORE settings, or it's falling off the end due to HISTSIZE?

1

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .