I recently switched from bash to zsh. In bash, one way (besides recursive search) that I used to find previously-run commands was history | grep whatever, where whatever is the bit of command I remember.
In zsh, this isn't working. history returns only a few items, even though my .zsh_history file contains many entries, which I have configured it to do.
How can I output my whole history, suitable for searching with grep?
3 Answers
History accepts a range in zsh entries as [first] [last] arguments, so to get them all run history 0.
To get the zsh help (at least with mind) type Alt-h over the history command and this will bring up the help for built-ins.
The accepted answer is correct, but it’s worth noting that you don’t need to call the external grep binary to do the search, since that ability is baked in. I have this function defined in my .zshrc:
histsearch() { fc -lim "*$@*" 1 }Notes:
fcis the zsh builtin that controls the interactive history.historyis equivalent tofc -l.The
-mflag requires a pattern, which must be quoted.The
-iflag adds a timestamp.fchas many more tricks up its sleeve (e.g. limiting the search to internal history for the current session). See thezshbuiltins(1)man page or the official documentation.
Edit (2021-01-27):
A major advantage of using this method over just grepping the zsh history file is you get human-readable timestamps via -i. Of course, this only works if you’ve enabled the saving of timestamps to the history file in the first place:
setopt EXTENDED_HISTORYOver the years, I’ve also added the -D flag to my function, which shows the runtime of the command in history. (This is again dependent on EXTENDED_HISTORY.) Plus, I’ve renamed the function to hgrep, which I find easier to remember:
hgrep () { fc -Dlim "*$@*" 1 } 6 Have a look at fzf. It helps not only finding "whatever-particles" in your shell history, but also in other interesting places, e.g. browser history, directory history, etc.
fzf is a command-line fuzzy finder. That means you can search for particles or fractions of what you are looking for and it will display a collection of matches which you can continuously refine. It's really a game changer.
The homepage of the author contains a number of illustrative examples.
2