User Tools

Site Tools


search_command_line_history_using_glob_pattern_matching

This is an old revision of the document!


Task

The goal here is to quickly search the command line history using glob pattern matching.

Situation

When reverse searching the command line history using ctrl-r, a lot of characters have to be typed before arriving at the correct command. For example, to go to “cd ~/work/gitlab/rutils”, one approach is to

ctrl-r
cd<space>

and keep hitting ctrl-r until arriving at

cd ~/work/gitlab/rutils

Another approach is to

ctrl-r
cd ~/work/gitlab/r
<enter>

Here almost the entire command had to be typed since the user did many “cd ~/work/gitlab/xxx” type of commands after doing “cd ~/work/gitlab/rutils”.

Ideally, we want to avoid all this typing and get to the final command by typing a few keywords - say cd, rutils.

Solution

Add the following lines to ~/.zshrc.

# Use glob patterns when using ctrl-r
#   ctrl-r wordA*wordB
# will match commands where wordA is followed by wordB with zero or more number
# of characters in between. This functionality is not available in old zsh
# versions (ex:- 4.2.6) so check for its availability.
zle -al | grep -q history-incremental-pattern-search-backward
if [ $? -eq 0 ]; then
  bindkey "\C-r" history-incremental-pattern-search-backward
fi

After this

ctrl-r
cd*rutils

will match commands where cd is followed by rutils.

System Information

Tested this tip using zsh 5.0.7 on a machine running Debian Jessie.

% dpkg -l zsh | grep ^ii
ii  zsh            5.0.7-5      amd64        shell with lots of features

tags | reverse search using partial matches shell, reverse search using multiple words shell, use glob patterns in ctrl-r

search_command_line_history_using_glob_pattern_matching.1651756160.txt.gz · Last modified: 2022/05/05 13:09 by admin