A Bash prompt that shows the current Git branch reduces the chance of committing, rebasing, or deploying from the wrong checkout. The branch segment belongs in the prompt itself, so the active repository state is visible before each command.

Bash builds the prompt from PS1 each time it displays a new command line. A small helper function can ask Git for the current branch, print a formatted segment when the shell is inside a repository, and stay silent when the current directory is outside a repository or the checkout has no branch name.

The example below stores the helper in ~/.bashrc for interactive shells, loads it in a new Bash session, and verifies the prompt inside a temporary Git repository. The shell needs git on PATH, and command substitution inside PS1 depends on the default promptvars shell option.

Steps to show a Git branch in the Bash prompt:

  1. Back up the Bash startup file.
    $ cp ~/.bashrc ~/.bashrc.bak

    A broken prompt line in ~/.bashrc can make new interactive shells difficult to use until the line is fixed or removed.

  2. Open ~/.bashrc in a text editor.
    $ nano ~/.bashrc
  3. Add the Git branch helper and prompt assignment near the end of the file.
    ~/.bashrc
    __vcs_branch() {
        local branch
        branch=$(git branch --show-current 2>/dev/null) || return
        [ -n "$branch" ] && printf ' (%s)' "$branch"
    }
     
    PS1='\u@\h:\w$(__vcs_branch)\$ '

    Single quotes keep $(__vcs_branch) literal while the assignment is read. Bash expands it later each time the prompt is drawn. Place the assignment after any earlier PS1 line so the branch-aware prompt is the value Bash keeps.

  4. Check the startup file for syntax errors.
    $ bash -n ~/.bashrc

    No output means Bash did not find a parse error.

  5. Load the updated startup file in the current shell.
    $ source ~/.bashrc

    If the prompt shows $(__vcs_branch) literally, enable prompt variable expansion with shopt -s promptvars before testing again.

  6. Create a temporary Git repository for the prompt check.
    $ git init -b main ~/prompt-check
    Initialized empty Git repository in /home/user/prompt-check/.git/
  7. Enter the temporary repository.
    $ cd ~/prompt-check
  8. Start a new interactive Bash session with the updated startup file.
    $ bash --noprofile --rcfile ~/.bashrc
    user@host:~/prompt-check (main)$ exit
    exit

    The (main) segment confirms the prompt helper is reading the active Git branch.

  9. Return to the home directory.
    $ cd ~
  10. Remove the temporary repository.
    $ rm -rf ~/prompt-check