This guide covers how to show the current Git branch in your shell prompt without breaking line wrapping, history navigation, or prompt speed. It is a troubleshooting-first setup walkthrough with clean examples, escape rules, and lightweight branch detection logic tested across Linux jump hosts and local development machines. We will cover PS1 escape handling, branch display strategy, performance tradeoffs, and readable color choices, with follow-up context in the shell snippets reference.

Why most prompt snippets break over time

The common copy-paste prompt one-liner works for a while, then you see weird cursor jumps or broken wrapping after long commands. That usually means non-printing color sequences were not wrapped correctly, so Bash miscounts prompt width.

Bash escape behavior is documented in the GNU Bash manual at gnu.org. Use it as the source of truth whenever prompt behavior looks inconsistent.

Step 1: Add a branch helper

Put this in your shell rc file:

1
2
3
parse_git_branch() {
git symbolic-ref --short HEAD 2>/dev/null || git rev-parse --short HEAD 2>/dev/null
}

This returns branch name when available and short commit id in detached HEAD state.

Step 2: Wrap color escapes correctly

For Bash, non-printing sequences must be wrapped in \[ and \].

1
2
3
GREEN='\[\e[32m\]'
GRAY='\[\e[90m\]'
RESET='\[\e[0m\]'

Step 3: Build PS1 with conditional branch display

1
export PS1='${GRAY}\u@\h ${RESET}\w${GREEN}$(b=$(parse_git_branch); [ -n "$b" ] && echo " [$b]")${RESET}\$ '

Keep it simple. If you load many subprocess-heavy helpers in PS1, every prompt draw gets slower.

Readability tips

  • Avoid bright saturated colors that obscure directory context.
  • Keep branch marker compact, for example [main].
  • Use one branch color across machines for quick visual consistency.

Performance notes

On large repositories, Git status calls can be expensive. Prefer branch-only detection unless you specifically need dirty-state indicators.

Caution

If your prompt appears to split lines in the wrong place, review escaping first. Most prompt bugs are formatting math bugs, not shell bugs.

FAQ

Does this work in zsh?

The logic is similar, but prompt escape syntax differs. Use zsh-native prompt formatting there.

Can I show dirty state too?

Yes, but test speed in large repositories before keeping it enabled.

Should I use global shell config for all machines?

Use a shared base and machine-specific overrides for paths and host tags.