How to Change Your Zsh Shell Prompt

Published: Dec 2, 2022

I’ve written about this kind of thing before with Bash. Fast forward to now – I’m setting up a new MacBook Pro for work and the default shell for macOS Catalina, and onwards, is zsh.

I decided to give it a chance. Yes… I’m aware of Oh My Zsh and all the cool themes. But I’m the weird fella that likes to do things by hand to understand them first, then let myself get fancy. Okay, let’s jump in.

The default prompt config lives in the file /etc/zshrc as:

PS1="%n@%m %1~ %# "

Which shows a prompt like this:

username@hostname partial_current_dir %

I wanted a prompt like this, so that the full current dir and current git branch show, followed by a newline:

username@hostname full_current_dir (current_git_branch)
%

After a bunch of googling and doc reading, here’s what I ended up with. This lives in my ~/.zshrc file as:

setopt PROMPT_SUBST

format_current_git_branch() {
  local BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)
  if [[ -n ${BRANCH} ]] ; then
    echo "(${BRANCH})"
  fi
}

export NEWLINE=$'\n'

export PROMPT='%n@%m %~ $(format_current_git_branch) ${NEWLINE}%# '

Let’s break it down:

Bonus: You can make the full_current_dir cyan, and the (current_git_branch) yellow, by using the zsh text color syntax:

export PROMPT='%n@%m %F{cyan}%~%F{reset_color} %F{yellow}$(format_current_git_branch)%F{reset_color} ${NEWLINE}%# '

Start a color with %F{cyan} then reset it with %F{reset_color}. See supported colors.

See the Prompt Expansion docs for all possible config.