Last Updated: October 26, 2017
· w0ng

zsh: Better history searching with arrow keys

Desired behaviour:

Search through history for previous commands matching everything up to current cursor position. Move the cursor to the end of line after each match.


[] indicates the current cursor position. With the partial command:

$ rbenv exec[]

We want up arrow keypresses to result in:

$ rbenv exec rake generate[]
$ rbenv exec rake preview[]

and down arrow keypresses to result in:

$ rbenv exec rake preview[]
$ rbenv exec rake generate[]
$ rbenv exec[]


Add to ~/.zshrc:

autoload -U up-line-or-beginning-search
autoload -U down-line-or-beginning-search
zle -N up-line-or-beginning-search
zle -N down-line-or-beginning-search
bindkey "^[[A" up-line-or-beginning-search # Up
bindkey "^[[B" down-line-or-beginning-search # Down

More info:

  • man zshzle. Search for "History Control".
  • man zshcontrib. Search for "up-line-or-beginning-search".
Say Thanks

2 Responses
Add your response


Thanks for this. I was struggling to find the same solution myself. However, the "^[[A" and "^[[B" did not register as Up and Down in my terminal for some reason. [1] has an interesting lookup pattern that sets $key_info["Up"} = "$terminfo[kcuu1]"</code>--similarly for other special keys--and with that the Up and Down keys worked.


over 1 year ago ·

Thanks a lot for this tip.

I wanted to set this behavior to match my tcsh configuration:

bindkey -k up history-search-backward
bindkey -k down history-search-forward
28 days ago ·
Filed Under