How to Show the Git Branch in the Terminal Prompt on macOS

If you’re a developer working with Git on macOS, it can be incredibly helpful to have your current Git branch displayed right in your terminal prompt. This guide will walk you through the steps to set this up.

Step 1: Open Your Terminal

First, open the Terminal application on your Mac. You can find it in Applications > Utilities or by searching for “Terminal” in Spotlight.

Step 2: Edit Your Bash Profile

If you’re using the default shell in macOS, which is Zsh (macOS Catalina and later), you will need to edit the .zshrc file. For older versions of macOS using Bash, you will edit the .bash_profile file.

To open the file for editing, use the following commands:

  • For Zsh (macOS Catalina and later):
$ vi ~/.zshrc
  • For Bash (macOS Mojave and earlier):
$ vi ~/.bash_profile

Step 3: Add the Git Branch Display Code

Next, you need to add a function to display the current Git branch in your prompt. Depending on the shell you are using, add the corresponding code snippet to the file you opened.

  • For Zsh, add the following:
# Git branch in prompt
autoload -Uz vcs_info
precmd() { vcs_info }
setopt prompt_subst
PROMPT='%F{yellow}%n@%m%f %1~ %F{green}${vcs_info_msg_0_}%f %# '
zstyle ':vcs_info:git:*' formats '(%b)'
zstyle ':vcs_info:*' actionformats '(%b)'
  • For Bash, add the following:
# Git branch in prompt.
parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/
}
export PS1="\u@\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "

Other option:

# Git branch in prompt
parse_git_branch() {
  git branch 2>/dev/null | grep '*' | sed 's/* //'
}
PS1="\u@\h \w \[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "

Step 4: Apply the Changes

After adding the code, save the file and exit the editor.

To apply the changes, you need to reload the profile (or close the session / Terminal and reopen it). Use the following command based on the file you edited:

  • For Zsh:
$ source ~/.zshrc
  • For Bash:
$ source ~/.bash_profile

Step 5: Verify the Changes

Now, navigate to any Git repository using the cd command, and you should see the current Git branch name displayed in your terminal prompt. For example, if you’re on the master branch, your prompt might look something like this:

robermb@MacBook-Pro lab_ansible (master) $

And that’s it! You’ve successfully configured your terminal to display the current Git branch in the prompt on macOS.

Compartir:

This article was written by RoberMB

💻OS, ☁️Cloud, 🛡️Cybersecurity, ✈️Traveling #Linux, #Ansible, #AWS, #VMware, #Docker 🏴‍☠️ CEH v10, CPHE 🏴‍☠️ ... Always learning, always enjoying.

Leave a Reply

Your email address will not be published. Required fields are marked *