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?
1 Answer
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
?
-
Be careful with
Ctrl-S
: it can freeze your terminal unless you have done some re-configuration beforehand. Apr 27, 2011 at 12:38
history | grep <something>
then running!<number>
would be a way of doing it?