Skip to main content

Using Zsh

Using Command History in Zsh

Not getting command history in Zsh? Here's how to enable it.

When I switched to zsh, it came as a shock that there's no file to store the history of executed commands in zsh and for someone like me, history is one of the most crucial parts of using a terminal.

Don't worry! Zsh being one of the most customizable shells from its core, you can create a history file to store the previously executed commands.

So in this tutorial, I will walk you through how you can enable history in zsh.

How to enable history in zsh

If you are using a plugin like Oh My Zsh then you already have a history file in your system. So how do you identify if you already have it or not?

Simply print the value of the HISTFILE variable using the following:

echo $HISTFILE
Verify if zsh history file already exist or not

If you get an empty output like mine then you don't have a history file and refer to the instruction that I'm about to share.

To set up a history file, first, open the zshrc file using the following command:

nano ~/.zshrc

Once you open the zshrc file, go to the end of the file in the nano editor by pressing Alt + / and paste the following lines:

# History file for zsh
HISTFILE=~/.zsh_history

Next, save changes and exit from the nano editor. Source the file to take effect from the changes you've just made:

source ~/.zshrc

Specify how much to store in history

To specify how many commands you want to store in your zsh history, you'd have to specify the value through two variables: HISTSIZE and SAVEHIST.

First, open the configuration file using the following:

nano ~/.zshrc

Go to the end of the line and paste the following:

# How many commands to store in history
HISTSIZE=10000
SAVEHIST=10000
Specify how many commands to save in zsh history

Here,

  • HISTSIZE: it specifies the number of commands to be saved in your memory for the current zsh session.
  • SAVEHIST: here, you specify the number of commands to be saved in the history file.

Feel free to change the numbers according to your use 😃.

Once done, save the changes and exit from the file.

Share the same history in every terminal session

If you want to share the history of every terminal session then you have to use the SHARE_HISTORY option.

First, open the zshrc config file, go to the end of the file, and paste the following line of code:

# Share history in every terminal session
setopt SHARE_HISTORY
Share zsh history among every active terminal session

Save changes, exit the editor, and don't forget to source file.

Putting everything together

Here's a summary of this tutorial in case you want to copy everything and make your config like mine instantly:

# History file for zsh
HISTFILE=~/.zsh_history

# How many commands to store in history
HISTSIZE=10000
SAVEHIST=10000

# Share history in every terminal session
setopt SHARE_HISTORY

Have a question or a suggestion? Drop a comment.