Options and shared history

Zsh · Practical · 10 min

A handful of options and history settings make the shell noticeably nicer to live in.

Most zsh behaviour is controlled by named options. setopt NAME turns one on, unsetopt NAME (or setopt NO_NAME) turns it off. Names are case-insensitive and underscores are ignored, so AUTO_CD, autocd and AutoCd are the same option. Plain setopt lists the options that differ from their defaults, and [[ -o name ]] tests one.

Popular interactive options:

  • AUTO_CD: type a directory name alone to cd into it,
  • AUTO_PUSHD and PUSHD_IGNORE_DUPS: every cd pushes onto a stack; cd -<Tab> and dirs -v let you jump back,
  • INTERACTIVE_COMMENTS: allow # comments at the prompt (off by default!),
  • CORRECT: offer to fix mistyped commands.

History is not saved unless you configure it. Set HISTFILE to a path, HISTSIZE (entries kept in memory) and SAVEHIST (entries written to the file). Then add:

  • SHARE_HISTORY: all open shells read and append to the same history as you go,
  • HIST_IGNORE_ALL_DUPS: drop older duplicates,
  • HIST_IGNORE_SPACE: commands typed with a leading space are not recorded, useful for secrets,
  • EXTENDED_HISTORY: store timestamps and durations.

history (an alias of fc -l) shows entries; history -i adds ISO timestamps, and !!, !$ and !git history expansion work as in bash.

Example

# ~/.zshrc
setopt AUTO_CD                        # 'projects' alone -> cd projects
setopt AUTO_PUSHD PUSHD_IGNORE_DUPS   # cd builds a stack: cd -<Tab>, dirs -v
setopt INTERACTIVE_COMMENTS           # allow # comments at the prompt
setopt CORRECT                        # zsh: correct 'gti' to 'git' [nyae]?
HISTFILE=~/.zsh_history
HISTSIZE=50000                        # entries kept in memory
SAVEHIST=50000                        # entries written to HISTFILE
setopt SHARE_HISTORY                  # all shells share one live history
setopt HIST_IGNORE_ALL_DUPS HIST_IGNORE_SPACE EXTENDED_HISTORY
# At the prompt:
setopt                                # options that differ from defaults
[[ -o autocd ]] && echo "autocd on"   # case and underscores do not matter
history -i -5                         # last 5 entries with timestamps

Remember

  • setopt / unsetopt; names ignore case and underscores
  • History is only saved with HISTFILE and SAVEHIST set
  • SHARE_HISTORY and HIST_IGNORE_SPACE are the favourite history options

Watch out for

  • Expecting history to persist without setting HISTFILE and SAVEHIST.

Check yourself

  1. Which pair of settings is needed for zsh to write history to disk?
  2. Are `setopt AUTO_CD` and `setopt autocd` the same?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: zsh.sourceforge.io/Doc/Release/Options.html