Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to get git status in bash

Tags:

git

bash

For a while now I've been using the __git_ps1 function in my bash's PS1 prompt (with PS1='\w$(__git_ps1)'). Now I want to color it depending on branch status.

I wrote a bash function that checks if the current branch is modified, and colors red or white depending on the status. The problem is that it uses git status to check the status (it's the only way I know off), and that's several times slower than __git_ps1, which is enough to cause an annoying delay when I'm using the prompt (I'm on a very weak netbook).

So I ask: is there a faster way to check status of the current git folder? __git_ps1 is a lot faster than manually parsing git branch, so I'm thinking there might be some other hidden git function.

like image 776
Malabarba Avatar asked Jun 20 '12 15:06

Malabarba


1 Answers

! git diff-index --cached --quiet HEAD      # fastest staged-changes test
! git diff-files --quiet                    # fastest unstaged-changes test
! git diff-index --quiet          HEAD      # fastest any-changes test
stdbuf -oL git ls-files -o | grep -qs .     # fastest untracked-files test
git rev-parse -q --verify refs/stash >&-    # fastest any-stash test

If ignored status matters for untracked files use --exclude-standard -oi for untracked-ignored and --exclude-standard -o for untracked and unignored.

The fastest way I know to get a HEAD moniker (branch name or sha) is

{ git symbolic-ref -q --short HEAD || git rev-parse -q --short --verify HEAD; } 2>&-

which leaves a return code if you're not in a repo, so you can e.g.

if HEAD=`{ git symbolic-ref -q --short HEAD || git rev-parse -q --verify HEAD;  } 2>&-`
then
        : in a git repo, $HEAD is the branch name or sha
fi

NOTE that the untracked-files test depends on running with shopt -s lastpipe for bash. zsh and ksh operate that way by default.

like image 146
jthill Avatar answered Oct 12 '22 22:10

jthill