How can I search history with text already entered at the prompt in zsh?

You can use zle's history-search functionality:

bindkey "^[[A" history-beginning-search-backward
bindkey "^[[B" history-beginning-search-forward

This binds Up and Down (adjust for your own escape sequences) to a history search, backwards and forwards, based upon what has already been entered at the prompt.

So, if you were to enter "vim" and hit Up, zsh will traverse backwards through your history for only those commands commencing with "vim".

You can additionally have the cursor placed at the end of the line once you have selected your desired command from zsh's history by using the history-search-end function (typically located in /usr/share/zsh/functions/Zle/) and appending -end to the end of each line, like so:

autoload -U history-search-end
zle -N history-beginning-search-backward-end history-search-end
zle -N history-beginning-search-forward-end history-search-end
bindkey "^[[A" history-beginning-search-backward-end
bindkey "^[[B" history-beginning-search-forward-end

Another useful option is history | grep

Assign an alias, e.g.

alias hg='history | grep'

then you can type hg whatever to search for commands you've used, e.g.

$ hg chmod                                                                                                       
 1309  chmod +x rotate_files.sh 
 1385  chmod +x rotate_files_270.sh 
 1512  chmod +x testy.sh 
 1528  chmod +x act_on_2_numbers.sh 
 2142  chmod +x ~/bin/display_tmux_pane_pwd.sh
 4532  chmod +x cat_files.rb 

I put this alias in my dot files.


If you are using oh-my-zsh, add history-substring-search to the plugins=(...) line.

Then add

bindkey "^[[A" history-substring-search-up
bindkey "^[[B" history-substring-search-down

somewhere below the line that read source $ZSH/oh-my-zsh.sh. Save and fire up a new terminal or run source ~/.zshrc in the current terminal.

Note: ^[[A is the escape sequence for up arrow in the terminal I use (kitty) and many others. To check in your terminal of choice, type in showkey -a and then press they key you want to find the escape sequence for.