Skip to content

Instantly share code, notes, and snippets.

@reinvanoyen
Last active July 3, 2024 14:26
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

@jftuga
Copy link

jftuga commented Jun 14, 2024

I have a two line prompt:

  • line 1: current directory [git branch]
  • line 2: HH:MM:SS $
function parse_git_branch() {
    git branch 2> /dev/null | sed -n -e 's/^\* \(.*\)/[\1]/p'
}
COLOR_DEF=$'%f'
COLOR_DATE=$'%F{243}'
COLOR_DIR=$'%F{197}'
COLOR_GIT=$'%F{39}'
setopt PROMPT_SUBST
PROMPT_CWD='${COLOR_DIR}%~ ${COLOR_GIT}$(parse_git_branch)${COLOR_DEF}'
export NEWLINE=$'\n'
export PROMPT="${NEWLINE}${PROMPT_CWD}${NEWLINE}${COLOR_DATE}%D{%H:%M:%S}${COLOR_DEF} $ "

I don't need USER, so I changed COLOR_USER to COLOR_DATE.

Here is what it looks like, with the directory name in red, the branch in blue, and the date in faded gray:

~/go/src/github.com/jftuga/dtdiff [dev]
17:35:28 $ 

What I like about having the time:

  • If I meant to time something, but forgot to, I have a built-in timer of sorts
  • I can easily scroll back to see how long ago I ran a command

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