Skip to content

Instantly share code, notes, and snippets.

@reinvanoyen
Last active February 25, 2025 10:17
Show Gist options
  • Save reinvanoyen/05bcfe95ca9cb5041a4eafd29309ff29 to your computer and use it in GitHub Desktop.
Save reinvanoyen/05bcfe95ca9cb5041a4eafd29309ff29 to your computer and use it in GitHub Desktop.
Add Git Branch Name to Terminal Prompt (MacOS zsh)

Add Git Branch Name to Terminal Prompt (zsh)

Updated for MacOS with zsh

  • Catalina
  • Big Sur
  • Monterey
  • Ventura
  • Sonoma

screenshot

Install

Open ~/.zshrc in your favorite editor and add the following content to the bottom.

function parse_git_branch() {
    git branch 2> /dev/null | sed -n -e 's/^\* \(.*\)/[\1]/p'
}

COLOR_DEF=$'%f'
COLOR_USR=$'%F{243}'
COLOR_DIR=$'%F{197}'
COLOR_GIT=$'%F{39}'
setopt PROMPT_SUBST
export PROMPT='${COLOR_USR}%n ${COLOR_DIR}%~ ${COLOR_GIT}$(parse_git_branch)${COLOR_DEF} $ '

Reload and apply adjustments

To reload and apply adjustments to the formatting use source ~/.zshrc in the zsh shell.

Credits

@SaraForesti
Copy link

That's great, thank you! Just one issue: I have to run the source ~/.zshrc (in my case source ~/.zprofile) command each time I open a new terminal tab or window. Is there a way to run this automatically?

The ~/. zprofile file is only evaluated when you login to your mac user account. The . zshrc (environment for interactive shells) should be used for parameters like $PROMPT, aliases, functions, options, history variables and bind keymappings you would like to have in both login and interactive shells.

What's preventing you from using the .zshrc file?

Thanks for the reply.
When I installed nvm via Homebrew, I got these 3 items created
.zprofile

.zsh_history

.zsh__sessions (folder)
I thought .zshrc would be one of them (It's been a while since last time I've done this for a new machine!), but since it wasn't there, I've done some research and found out that .zshrc and .zprofile should be the same: I guess they are not!

I'll try create a .zshrc manually then.

@gtt116
Copy link

gtt116 commented Dec 11, 2024

That is awesome

@gabrieljuniorcreditas
Copy link

Nice! Worked for me. Thank you!

@ethaizone
Copy link

Thank you. I used your version for sometimes until I think I need some adjustment for git status so I created new gist.

Other can use as well or just copy git_status function to your zshrc file and change your exist prompt.
https://gist.github.com/ethaizone/232664a147258fb6a5b91ba2bf790f37

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment