Join my Laravel for REST API's course on Udemy 👀

Command history in ZSH

March 30, 2021  ‐ 2 min read

If you're a user of oh-my-zsh most of the history are taken care of already. However, when you're setting up ZSH from scratch yourself you need to configure some settings before the command history is up and running.

First, the file where the history will be stored. Unlike Bash, Zsh doesn't provide a default location for where to store command history. So you need to set it yourself in your ~/.zshrc config file. I went for the file name .zsh_history but feel free to set this to whatever you prefer, it also doesn't need be located in your home director.

# ~/.zshrc

# The file where the history is stored
export HISTFILE="$HOME/.zsh_history"

Second is related to the length of the history file; how much command you will keep in history. There are two environment variables that relate to this. First is the HISTSIZE variable, which defines how many commands are loaded into memory from the history file. Second is the SAVEHIST variable, which defines how many commands are stored in the history file.

# ~/.zshrc

# Number of events loaded into memory
export HISTSIZE=10000

# Number of events stored in the zsh history file
export SAVEHIST=10000

That covers at least the basics. Next are a couple options I personally prefer as well.

# ~/.zshrc

# Do not save duplicate commands to history
setopt HIST_IGNORE_ALL_DUPS

# Do not find duplicate command when searching
setopt HIST_FIND_NO_DUPS

Clear history

Since the ZSH history is just kept in a file, clearing the history is just clearing the file. You can easily clear the contents of a file with a single command:

$ truncate -s 0 "${HISTFILE}"

Show all historic commands

To show the entire ZSH history you can open the history file with your preferred pager:

$ less "${HISTFILE}"