A Zsh prompt that shows the active Git branch makes repository context visible before each command. That context matters before commits, rebases, deployments, and cleanup commands where the wrong branch can change the wrong code.
Zsh includes vcs_info for version-control prompt metadata. It reads the current repository state, writes a formatted result to vcs_info_msg_0_, and can refresh from a precmd hook before each prompt is drawn.
The configuration belongs in the interactive Zsh startup file, usually ~/.zshrc. Back up that file before changing PROMPT, enable prompt substitution so the refreshed variable expands at display time, and place the block after any theme or framework that rewrites the prompt.
Related: How to customize the Zsh prompt with PS1
Related: How to configure Zsh startup files
Steps to show a Git branch in the Zsh prompt with vcs_info:
- Back up the current interactive startup file.
$ test -f ~/.zshrc && cp ~/.zshrc ~/.zshrc.bak
No output means the backup command found no existing file to copy or copied the file without reporting a message. If ZDOTDIR is set, back up $ZDOTDIR/.zshrc instead.
- Open the interactive Zsh startup file.
$ vi ~/.zshrc
If ZDOTDIR is set, edit $ZDOTDIR/.zshrc instead of ~/.zshrc.
- Add the vcs_info prompt setup near the end of the file.
- ~/.zshrc
autoload -Uz vcs_info add-zsh-hook zstyle ":vcs_info:git:*" formats "(%b)" prompt_vcs_info() { vcs_info } add-zsh-hook precmd prompt_vcs_info setopt prompt_subst PROMPT='${vcs_info_msg_0_:+$vcs_info_msg_0_ }%# '
add-zsh-hook attaches the refresh without replacing an existing precmd function. Replace only the PROMPT assignment if the rest of the file already sets colors, host names, or path segments that should stay visible.
- Check the startup file for syntax errors.
$ zsh -n ~/.zshrc
No output means Zsh accepted the file syntax.
- Create a temporary Git repository when no safe test repository is available.
$ git init -b main repo Initialized empty Git repository in /home/operator/repo/.git/
- Enter the repository.
$ cd repo
- Verify the branch segment in a new interactive Zsh process.
$ zsh -ic 'vcs_info; print -r -- "segment=$vcs_info_msg_0_"' segment=(main)
The check calls vcs_info once because a non-tty command exits before drawing a normal prompt.
- Open a new interactive Zsh terminal in the repository.
The prompt should show (main) before the prompt character. If it does not change, check whether a later theme or prompt framework is replacing PROMPT after the vcs_info block runs.
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.