Ramblings of an aging IT geek
← Ramblings of an aging IT geek
tooling

building a prompt that earns its space

How I rebuilt my zsh prompt to show git state, exit codes and the current Kubernetes context without becoming a christmas tree.

A keyboard and a terminal at night

I spent an evening rebuilding my shell prompt, which is the sort of yak-shaving I would mock in a colleague. But I do this dozens of times a day, and a prompt that tells me the right thing at a glance saves more time than the evening cost. The goal was simple: show me what I need to know to not do something stupid, and nothing else.

What I actually want to see

The list is short, which is the point. I want the current directory, the git branch and whether the tree is dirty, the exit code of the last command but only when it failed, and the active Kubernetes context, because running the right command against the wrong cluster is a uniquely modern way to ruin an afternoon.

Everything else is noise. The hostname I already know, the username is almost always me, and the full path eats half the line for no reason.

A close-up of code on screen

The build

I am on zsh, so this lives in .zshrc. The git bit uses vcs_info, which ships with zsh and is far less effort than parsing git status myself.

autoload -Uz vcs_info
precmd() { vcs_info }
zstyle ':vcs_info:git:*' formats ' %F{yellow}%b%f'
zstyle ':vcs_info:git:*' check-for-changes true
zstyle ':vcs_info:git:*' unstagedstr ' %F{red}*%f'

setopt prompt_subst
PROMPT='%F{blue}%1~%f${vcs_info_msg_0_} %(?..%F{red}%?%f )%# '

The clever-ish part is %(?..%F{red}%?%f ). That only prints the exit code when it is non-zero. A green prompt that stays quiet when things work, and shouts a red number when they do not, is exactly the signal-to-noise ratio I wanted.

The Kubernetes context I add on the right with RPROMPT, pulled from kubectl config current-context but cached so I am not shelling out on every prompt redraw. Calling kubectl synchronously before each prompt makes the shell feel sticky, and a sticky shell is worse than no context display at all.

Worth it?

A week in, yes. The dirty-tree marker has stopped me committing to the wrong branch twice, and the cluster context on the right has stopped me doing something far worse at least once. A prompt is a tiny heads-up display you stare at all day. It is worth getting right, and then never touching again. I have given myself a strict rule: no more prompt tinkering until something genuinely annoys me. We will see how long that lasts.