Skip to content
Hands-on IT IT Drills

Day 2: zsh basics

Goal: You know which startup file runs when, you have a clean PATH, good completion and a measurably fast shell. · Duration: approx. 75 min · Prerequisite: Day 0

Briefing

  • zsh reads up to five startup files of your own. Which ones depends on whether the shell is a login shell and/or interactive.
  • macOS starts a login shell in every new terminal tab. In the process, /etc/zprofile rearranges the PATH.
  • You control behavior with setopt. You load completion with compinit and configure it with zstyle.
  • You pay for every millisecond of startup time with every tab and every tmux pane. Measure it.
              .zshenv  .zprofile  .zshrc  .zlogin  .zlogout
 login+inter.    1         2        3        4      5 (exit)
 inter. only     1                  2
 script/-c       1

Before each of your own files, zsh reads the system variant from /etc (/etc/zshenv, /etc/zprofile, /etc/zshrc, …), if present.

Drill 1: Making the order visible

A throwaway ZDOTDIR in which each file only prints its name:

T=~/term-lab/zsh-trace
mkdir -p $T
for f in .zshenv .zprofile .zshrc .zlogin .zlogout; do
  echo "echo $f" > $T/$f
done
echo "== Login + interaktiv"; ZDOTDIR=$T zsh -l -i -c true
echo "== nur interaktiv";     ZDOTDIR=$T zsh -i -c true
echo "== Skript";             ZDOTDIR=$T zsh -c true

Expected:

== Login + interaktiv
.zshenv
.zprofile
.zshrc
.zlogin
.zlogout
== nur interaktiv
.zshenv
.zshrc
== Skript
.zshenv

Three rules follow from this:

File What belongs in it What doesn’t
.zshenv variables that scripts need too (EDITOR, LAB) output, aliases, slow commands
.zprofile one-time login stuff, e.g. brew shellenv anything interactive
.zshrc everything interactive: options, completion, prompt, aliases variables that scripts need

You’ll practically never need .zlogin and .zlogout.

Save your progress? Sign up for free

Drill 2: Why the PATH tips over on the Mac

Now a typical mistake: prepending Homebrew to the PATH in .zshenv.

echo 'path=(/opt/homebrew/bin $path)' > $T/.zshenv
rm $T/.zprofile $T/.zshrc $T/.zlogin $T/.zlogout
env -i HOME=$HOME TERM=$TERM PATH=/usr/bin:/bin ZDOTDIR=$T \
  zsh -l -i -c 'print -l $path | grep -n .'

Expected (shortened):

1:/usr/local/bin
2:/System/Cryptexes/App/usr/bin
3:/usr/bin
4:/bin
5:/usr/sbin
6:/sbin
...
11:/opt/homebrew/bin

/opt/homebrew/bin is no longer at the front but in position 11. The culprit is /etc/zprofile: it runs after .zshenv and calls path_helper. That puts the entries from /etc/paths at the beginning. The result: git is suddenly Apple’s version from /usr/bin, not Homebrew’s.

which -a git

Expected:

/opt/homebrew/bin/git
/usr/bin/git

That’s how it should look in your lab shell. The rule that follows: PATH changes belong in .zprofile or .zshrc, never in .zshenv. That’s exactly why Homebrew writes eval "$(/opt/homebrew/bin/brew shellenv)" into .zprofile during installation.

By the way, env -i starts with an empty environment. That way you see what the startup files alone do.

Clean up: rm -rf ~/term-lab/zsh-trace.

Save your progress? Sign up for free

Drill 3: Extending the lab .zshrc

Replace the starter .zshrc from Day 0 with a proper version:

cat > ~/term-lab/zsh/.zshrc <<'EOF'
# ~/term-lab/zsh/.zshrc – as of Day 2
# --- PATH: unique, own scripts first ----------------------------------
typeset -U path PATH fpath FPATH
path=("$LAB/bin" /opt/homebrew/bin /opt/homebrew/sbin $path)
fpath=(/opt/homebrew/share/zsh/site-functions $fpath)

# --- Options ----------------------------------------------------------
setopt AUTO_CD AUTO_PUSHD PUSHD_IGNORE_DUPS PUSHD_SILENT
setopt INTERACTIVE_COMMENTS EXTENDED_GLOB NO_BEEP
bindkey -e                  # Emacs keys, even though EDITOR=nvim (Day 3)

# --- Completion -------------------------------------------------------
autoload -Uz compinit
compinit -d "$ZDOTDIR/.zcompdump"
zstyle ':completion:*' menu select
zstyle ':completion:*' matcher-list 'm:{a-z}={A-Za-z}'
zstyle ':completion:*:descriptions' format '%F{yellow}-- %d --%f'
zstyle ':completion:*' use-cache on
zstyle ':completion:*' cache-path "$ZDOTDIR/.zcompcache"

# --- Prompt: exit code only on error ----------------------------------
PROMPT='%F{yellow}[lab]%f %F{cyan}%1~%f %(?..%F{red}%?%f )%# '

# --- own files (from Day 5) -------------------------------------------
for f in "$LAB"/config/zsh/*.zsh(N); do source "$f"; done
EOF
exec ~/term-lab/lab
print -l $path[1,3]
print -l $path | sort | uniq -d | wc -l

Expected:

/Users/du/term-lab/bin
/opt/homebrew/bin
/opt/homebrew/sbin
       0

Why like this?

  • typeset -U path makes the array unique. Otherwise duplicate entries appear in every nested shell, for example in tmux.
  • path and PATH are tied together in zsh. With the array you work without fiddling with colons.
  • fpath is the search path for functions and completions. Homebrew puts _git, _brew, _gh and co. there.
  • (N) on the glob is a qualifier: no error message if the folder is empty (Day 3).
  • bindkey -e forces the Emacs key bindings. Without that line, zsh switches to vi mode because of EDITOR=nvim (Day 3).
  • The prompt shows the exit code in red, but only if it’s not 0: %(?..text).

Test the error prompt:

false
true

Expected:

[lab] ~ % false
[lab] ~ 1 % true
[lab] ~ %

Save your progress? Sign up for free

Drill 4: Reading and toggling options

setopt

Expected (in a real terminal, may differ):

autocd
autopushd
nobeep
combiningchars
extendedglob
interactive
interactivecomments
monitor
pushdignoredups
pushdsilent
shinstdin
zle

setopt without an argument only shows what differs from the default. Case and underscores don’t matter: AUTO_CD, autocd and Auto_Cd are the same option.

[[ -o autocd ]] && echo "autocd an"
unsetopt autocd
echo $options[autocd]
setopt autocd

Expected:

autocd an
off

The associative array $options is handy in scripts. All options with explanations are in man zshoptions.

Option Effect
AUTO_CD projekt instead of cd projekt, .. instead of cd ..
AUTO_PUSHD every cd puts the old directory on the stack
PUSHD_IGNORE_DUPS no duplicates on the stack
INTERACTIVE_COMMENTS # works as a comment interactively too
EXTENDED_GLOB ^, ~, # and qualifiers in globs (Day 3)

Save your progress? Sign up for free

Drill 5: The directory stack

cd ~/term-lab/projekt
cd internal/cart
cd ../../deploy/k8s
cd ~/term-lab
dirs -v

Expected:

0   ~/term-lab
1   ~/term-lab/projekt/deploy/k8s
2   ~/term-lab/projekt/internal/cart
3   ~/term-lab/projekt
4   ~
cd -2

Expected:

~/term-lab/projekt/internal/cart

Even faster: cd - and then ⇥. zsh shows the stack as a menu, you pick with the arrow keys. And thanks to AUTO_CD, the folder name alone is enough:

cd ~/term-lab
projekt
..

Expected:

[lab] term-lab % projekt
[lab] projekt % ..
[lab] term-lab %

Save your progress? Sign up for free

Drill 6: Completion like a pro

The menu gets a backward key too:

cat >> ~/term-lab/zsh/.zshrc <<'EOF'

# --- Completion menu: ⇧⇥ backwards ------------------------------------
zmodload zsh/complist
bindkey -M menuselect '^[[Z' reverse-menu-complete
EOF
exec ~/term-lab/lab
zstyle -L ':completion:*' | head -3
bindkey -M menuselect '^[[Z'

Expected:

zstyle ':completion:*' cache-path /Users/du/term-lab/zsh/.zcompcache
zstyle ':completion:*:descriptions' format '%F{yellow}-- %d --%f'
zstyle ':completion:*' matcher-list 'm:{a-z}={A-Za-z}'
"^[[Z" reverse-menu-complete

Now by hand, each without ⏎:

Input What happens
git sw⇥ completes to git switch
git switch ⇥ menu with feature/rabatt and main
cd proj⇥ in ~/term-lab completes projekt/
cd PROJ⇥ works in uppercase too, thanks to matcher-list
kill ⇥ process list with PID and command
ls -⇥ all options with descriptions
git ⌃Xh shows which completion function applies

In the menu you move with ⇥, ⇧⇥ and the arrow keys. ⏎ accepts, ⌃G cancels.

Where do the completions come from? From fpath:

whence -v _git _gh _kubectl

Expected:

_git is an autoload shell function
_gh is an autoload shell function
_kubectl is an autoload shell function

Tip: If a tool has no file in /opt/homebrew/share/zsh/site-functions, it usually generates one itself, e.g. atuin gen-completions --shell zsh. Write the output once as _atuin into a folder in fpath, instead of regenerating it on every start with source <(...).

Save your progress? Sign up for free

Drill 7: Measuring startup time

Three shells compared: without any configuration, your lab shell, your real shell.

hyperfine -N -w 3 -r 20 'zsh -f -i -c exit' \
  "env ZDOTDIR=$HOME/term-lab/zsh zsh -i -c exit" \
  'zsh -i -c exit'

Expected (shortened, your numbers will differ):

Benchmark 1: zsh -f -i -c exit (20 runs)
  Wall Time      2.2 ms  ±     0.2 ms       2.0 ms  …     2.6 ms
Benchmark 2: env ZDOTDIR=/Users/du/term-lab/zsh zsh -i -c exit (20 runs)
  Wall Time     30.2 ms  ±     0.8 ms      29.1 ms  …    32.1 ms
Benchmark 3: zsh -i -c exit (20 runs)
  Wall Time     63.8 ms  ±     3.4 ms      59.4 ms  …    71.6 ms

-N starts without an intermediate shell, -w 3 warms up the cache. Rule of thumb: under 50 ms you won’t notice anything. Over 200 ms, every new tab gets annoying. Frameworks like oh-my-zsh quickly end up at 300 ms and more. That’s why many senior engineers switch to a lean .zshrc plus starship.

Where does the time go? The zprof profiler shows it per function:

ZDOTDIR=~/term-lab/zsh zsh -i -c \
  'zmodload zsh/zprof; source $ZDOTDIR/.zshrc; zprof | head -4'

Expected (shortened, your numbers will differ):

num  calls                time                       self            name
-----------------------------------------------------------------------------------
 1)    2          11,39     5,69   62,02%     11,39     5,69   62,02%  compaudit
 2)    1          18,36    18,36  100,00%      6,97     6,97   37,98%  compinit

The lion’s share is compaudit: the security check of all completion folders. The challenge makes it cheaper.

Save your progress? Sign up for free

Shortcut table

Key Effect Mnemonic
⇥ complete, twice: menu Tab = save typing
⇧⇥ backwards in the menu Shift = back
⌃G cancel the menu Go away
⌃D list possibilities (in the middle of the line) Display
⌃Xh which completion applies here? help
cd -⇥ directory stack as a menu minus = back
.. one level up (AUTO_CD) two dots

Checkpoint

LAB=${LAB:-~/term-lab}
ok() { local m=$1; shift; "$@" >/dev/null 2>&1 && echo "✔ $m" || echo "✘ $m"; }
lab() { env ZDOTDIR="$LAB/zsh" zsh -i -c "$1" 2>/dev/null; }
ms=$(LAB=$LAB zsh -fc 'zmodload zsh/datetime; s=$EPOCHREALTIME
  repeat 10 { ZDOTDIR=$LAB/zsh zsh -i -c exit }
  printf "%.0f" $(( (EPOCHREALTIME - s) * 100 ))')
ok "kein doppelter PATH"  test -z "$(lab 'print -l $path | sort | uniq -d')"
ok "Homebrew-git zuerst"  test "$(lab 'whence -p git')" = /opt/homebrew/bin/git
ok "AUTO_CD an"           lab '[[ -o autocd ]]'
ok "Completion geladen"   lab '(( $+functions[compdef] ))'
ok "Start ${ms} ms < 100" test "$ms" -lt 100

Expected (your number will differ):

✔ kein doppelter PATH
✔ Homebrew-git zuerst
✔ AUTO_CD an
✔ Completion geladen
✔ Start 30 ms < 100

$EPOCHREALTIME from the zsh/datetime module is a clock with microseconds. Ten starts, times 100, gives the average in milliseconds.

Challenge

compaudit checks all completion folders on every start. Make sure the full check runs only once a day and the cache in .zcompdump is enough otherwise. Measure before and after.

Hint: compinit -C skips the check. The glob qualifier (#qN.mh+24) matches only files older than 24 hours.

Solution

In ~/term-lab/zsh/.zshrc, replace the compinit -d … line with:

if [[ -n $ZDOTDIR/.zcompdump(#qN.mh+24) ]]; then
  compinit -d "$ZDOTDIR/.zcompdump"        # once a day: full check
else
  compinit -C -d "$ZDOTDIR/.zcompdump"     # otherwise: cache without audit
fi
hyperfine -N -w 3 -r 20 "env ZDOTDIR=$HOME/term-lab/zsh zsh -i -c exit"

Expected (shortened, your numbers will differ):

  Wall Time     21.4 ms  ±     0.6 ms      20.9 ms  …    23.2 ms

From 30 down to 21 ms, almost a third. The qualifier reads like this: #q = qualifier allowed in [[ ]], N = no error without a match, . = regular file, mh+24 = modification time more than 24 hours ago. If .zcompdump is missing entirely, compinit -C creates it anew.

Save your progress? Sign up for free

Enterprise Note

  • Company Macs often bring their own entries in /etc/paths.d or /etc/zshrc (VPN clients, security agents). zsh -o sourcetrace -l -i -c exit shows you in seconds who has a say.
  • .zshenv also runs in every script, in cron and in CI jobs that use zsh. Output or slow commands there break automation. Keep it minimal.
  • compaudit reports “insecure directories” when completion folders are writable by others. Don’t suppress that with compinit -u; repair the permissions instead: compaudit | xargs chmod g-w,o-w.
  • Share a common base in the team (options, completion, PATH) as a file in the dotfiles repo. Personal stuff goes into a local extra file that doesn’t belong in the repo (Day 13).
  • Server shells are often bash. What you learn here largely applies there too. Differences: shopt instead of setopt, .bashrc and .bash_profile instead of the zsh files.