Updated Feb 8, 2011: Handle indescribable HEAD (can happen during conflicts).
When I work with Git repositories, I like to have a visual cue as to whether there are modifications in my working copy. Here’s a snippet for your
~/.bashrc to insert info about your
git status into your bash prompt in a concise but informative fashion, as in the screenshot on the right:
- Green: Pristine working copy
- Yellow: No modifications, but untracked files present
- Red: Some files are modified (doesn’t matter if staged or not)
On the upside, it’s extremely fast: It does with one single call to
git (two on detached heads), and no calls to other binaries (like grep, sed, etc.), so your shell won’t feel sluggish. On the downside, it parses porcelain output, so it might break in some future version of Git. I think that’s a reasonable tradeoff to get maximum speed, though.
If you are on a branch other than
master, it also displays the current branch inside the colored box (see the screenshot at the bottom).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
In case anyone cares, the awkward dance of re-setting
$PROMPT_COMMAND seems to be necessary, since:
- Naively using
echo -nto dump out the status indicator from inside
_prompt_commandwould make Bash hiccup on the zero width of the ANSI sequences. (That’s what the magic
$PS1are for – they tell Bash that everything in between is non-printing, and hence not to be counted for line editing.)
- Also, apparently you cannot set
PS1='(note the single quotes): While
_git_prompt… your prompt …’
_git_promptdoes get interpolated every time the prompt is displayed, the special backslash sequences don’t get re-interpreted. (And echoing raw escape characters doesn’t solve our problem, since we still need
Here is a longer screenshot: