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.
Related: How to customize the Bash prompt
Related: How to configure Bash login scripts
Related: How to use command substitution in Bash
Tool: Prompt String 1 (PS1) Generator
$ 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.
$ nano ~/.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.
$ bash -n ~/.bashrc
No output means Bash did not find a parse error.
$ source ~/.bashrc
If the prompt shows $(__vcs_branch) literally, enable prompt variable expansion with shopt -s promptvars before testing again.
$ git init -b main ~/prompt-check Initialized empty Git repository in /home/user/prompt-check/.git/
$ cd ~/prompt-check
$ bash --noprofile --rcfile ~/.bashrc user@host:~/prompt-check (main)$ exit exit
The (main) segment confirms the prompt helper is reading the active Git branch.
$ cd ~
$ rm -rf ~/prompt-check