Permanent shell history in zsh

I like to keep a permanent record of my shell commands so I can search back through them later. This involves two steps:

  1. Setup your zsh to save the history on each invocation
  2. Create an alias to quickly search through the commands, with the newest on top

Place the following in your ~/.zshrc file

setopt extended_history # save timestamp
setopt inc_append_history # add history immediately after typing a command
precmd() { # This is a function that will be executed before every prompt
    local date_part="$(/opt/homebrew/bin/gawk 'substr($0, 0, 1) == ":" {print;}' ~/.zsh_history | tail -1  | cut -c 3-12)"
    local fmt_date="$(date -j -f '%s' ${date_part} +'%Y-%m-%d %H:%M:%S')"
    # For newer versions of "date", comment the last line and uncomment the next line
    # local fmt_date="$(date -d @${date_part} +'%Y-%m-%d %H:%M:%S')"
    local command_part="$(tail -1 ~/.zsh_history | cut -c 16-)"
    if [ "$command_part" != "$PERSISTENT_HISTORY_LAST" ]
    then
        echo "${fmt_date} | ${command_part}"  >> ~/.sh_eternal_history
        export PERSISTENT_HISTORY_LAST="$command_part"
    fi
}

# Load alias commands
. ~/.zsh_aliases

Place the following in your ~/.zsh_aliases file:

alias findhist='tail -r ~/.sh_eternal_history | grep -m 10'

Load into the current session:

source ~/.zshrc

Invoke:

findhist "ls -la"
# find more than 10 by specifying `-m`:
findhist -m 25 "ls -la"

(Adapted from https://stackoverflow.com/a/30272351/3439097)

This article was updated on 2023-01-25

I'm nabeards.

I'm a full stack JavaScript developer.

I travel full time, a.k.a., Professional Wanderer, a.k.a., Digital Nomad.