How can I check if I have any uncommitted changes in my git repository:
from a script?
git-status
seems to always return zero with git version 1.6.4.2.
Great timing! I wrote a blog post about exactly this a few days ago, when I figured out how to add git status information to my prompt.
Here's what I do:
For dirty status:
# Returns "*" if the current git branch is dirty.
function evil_git_dirty {
[[ $(git diff --shortstat 2> /dev/null | tail -n1) != "" ]] && echo "*"
}
For untracked files (Notice the --porcelain
flag to git status
which gives you nice parse-able output):
# Returns the number of untracked files
function evil_git_num_untracked_files {
expr `git status --porcelain 2>/dev/null| grep "^??" | wc -l`
}
Although git diff --shortstat
is more convenient, you can also use git status --porcelain
for getting dirty files:
# Get number of files added to the index (but uncommitted)
expr $(git status --porcelain 2>/dev/null| grep "^M" | wc -l)
# Get number of files that are uncommitted and not added
expr $(git status --porcelain 2>/dev/null| grep "^ M" | wc -l)
# Get number of total uncommited files
expr $(git status --porcelain 2>/dev/null| egrep "^(M| M)" | wc -l)
Note: The 2>/dev/null
filters out the error messages so you can use these commands on non-git directories. (They'll simply return 0
for the file counts.)
Edit:
Here are the posts: