How can I check if I have any uncommitted changes in my git repository:
- Changes added to the index but not committed
- Untracked files
from a script?
git-status
seems to always return zero with git version 1.6.4.2.
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.
There may be a better combination of answers from this thread.. but this works for me... for your
.gitconfig
's[alias]
section ...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:
For untracked files (Notice the
--porcelain
flag togit status
which gives you nice parse-able output):Although
git diff --shortstat
is more convenient, you can also usegit status --porcelain
for getting dirty files:Note: The
2>/dev/null
filters out the error messages so you can use these commands on non-git directories. (They'll simply return0
for the file counts.)Edit:
Here are the posts:
Adding Git Status Information to your Terminal Prompt
Improved Git-enabled Shell Prompt
Assuming you are on git 1.7.0 or later...
After reading all of the answers on this page and some experimenting, I think the method that hits the right combination of correctness and brevity is:
While git allows for a lot of nuance between what's tracked, ignore, untracked but unignored, and so on, I believe the typical use case is for automating build scripts, where you want to stop everything if your checkout isn't clean.
In that case, it makes sense to simulate what the programmer would do: type
git status
and look at the output. But we don't want to rely on specific words showing up, so we use the--porcelain
mode introduced in 1.7.0; when enabled, a clean directory results in no output.Then we use
test -n
to see if there was any output or not.This command will return 1 if the working directory is clean and 0 if there are changes to be committed. You can change the
-n
to a-z
if you want the opposite. This is useful for chaining this to a command in a script. For example:This effectively says "either there are no changes to be made or set off an alarm"; this one-liner might be preferable to an if-statement depending on the script you are writing.
Why not encapsulate '
git status
with a script which:That way, you can use that 'enhanced' status in your script.
As 0xfe mentions in his excellent answer,
git status --porcelain
is instrumental in any script-based solutionThe simplest automatic test I use to detect dirty state = any changes including untracked files:
NOTE:
add --all
diff-index
does not notice untracked files.git reset
after testing error code to unstage everything back.An implementation from VonC's answer: