How to Add Timestamps to Your Shell Command History

It’s a common scenario: you’re trying to remember when you executed a certain command in your terminal, but all you see is a list of commands with no indication of when they were run. If only there was a way to see the exact date and time you executed each command!

Good news! Whether you’re using Bash or Zsh as your preferred shell, there’s a simple tweak you can make to add timestamps to your command history. In this article, we’ll walk you through the steps to achieve this.

For Bash Users

  1. Edit Your Bash Configuration:
    Start by opening up your ~/.bashrc file in your favorite text editor. If you’re not sure how to do this, you can use the nano editor by typing:

    nano ~/.bashrc
    
  2. Add the Timestamp Format:
    Scroll to the bottom of the file and add the following line:

    export HISTTIMEFORMAT="%d/%m/%y %T "
    
  3. Activate the Changes:
    Save and close the file. Now, you’ll need to restart your terminal or simply type:

    source ~/.bashrc
    

Now, whenever you enter the history command in your terminal, you’ll see each command accompanied by its execution date and time.

For Zsh Users

  1. Edit Your Zsh Configuration:
    Dive into your ~/.zshrc file using your preferred text editor. If you’re using nano, the command would be:

    nano ~/.zshrc
    
  2. Incorporate the Timestamp Format:
    At the end of the file, add:

    export HIST_STAMPS="mm/dd/yyyy"
    
  3. Apply the Changes:
    After saving and closing the file, either restart your terminal or run:

    source ~/.zshrc
    

Voila! Your Zsh command history will now display the date each command was run.

Note: Feel free to adjust the date and time format to your liking. The given format displays day/month/year and the time. You can customize this to suit your preferences.