How To Add Git Branch To Bash Prompt?

Published August 25, 2024

Problem: Displaying Git Branch in Bash Prompt

Bash prompts don't usually show the current Git branch. This can make it hard for developers to know which branch they're working on, especially when switching between branches in a project.

Solution: Using Git's Built-in Function

Implementing __git_ps1 Function

Git provides a built-in function called __git_ps1 that can display the current branch name in your Bash prompt. This function is part of the git-prompt.sh script and is available in Git versions 1.9.3 and later. The __git_ps1 function prints text that can be added to your Bash PS1 prompt, including the branch name.

Tip: Customize Git Branch Display

You can customize how the Git branch information is displayed by setting environment variables before sourcing git-prompt.sh. For example:

GIT_PS1_SHOWDIRTYSTATE=1
GIT_PS1_SHOWSTASHSTATE=1
GIT_PS1_SHOWUNTRACKEDFILES=1

These settings will show additional information about the repository state in your prompt.

Step-by-Step Guide

To add the Git branch to your Bash prompt:

  1. Find the git-prompt.sh file:

    • On macOS, use this command:
      find / -name 'git-prompt.sh' -type f -print -quit 2>/dev/null
    • On other systems, search for the file or download it from the Git repository.
  2. Add this line to your .bashrc file:

    source /path/to/git-prompt.sh

    Replace "/path/to/" with the actual path where you found or placed the git-prompt.sh file.

  3. Change the PS1 variable in your .bashrc file to include the Git branch:

    PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '

    This shows the username, hostname, current directory, and Git branch (if in a Git repository).

After making these changes, restart your terminal or run source ~/.bashrc to apply the new prompt settings. Your Bash prompt will now show the current Git branch when you're in a Git repository.