Summary:
- A commit is checked out: test
git rev-parse HEAD 1>/dev/null 2>&1
- A ref pointing to a commit exists: test
git rev-list -n 1 --all 1>/dev/null 2>&1
- Objects exist in the repo: test output of
git fsck
, git count-objects
, or the examine the contents of .git/objects
And now for the discussion!
If you want to know whether a commit is checked out, you can use git rev-parse HEAD
. There will be output, so you probably want to redirect to /dev/null
and just use the exit code. For all practical purposes, this will be good enough - doing normal things, it's pretty much impossible to end up without HEAD
pointing at anything. But it is possible, for example by deleting files in the .git directory. Depending on your script, this might be important - if you're about to blow away the .git directory, you want to be paranoid indeed.
If you want to see whether there are any refs at all with commits on them, you can use git rev-list -n 1 --all
. Again, there will be output (the SHA1 of the first commit encountered), so redirect to /dev/null
and check the exit code.
Finally, if you want to check if there are any commits - even if they aren't on any refs (you have to try really hard to get into this state) I'd probably just check for the presence of objects with git fsck
or git count-objects
- or failing that, list .git/objects
and check for anything besides info
and pack
(commands tend to fail if there is no file .git/HEAD
). And yes, you could actually have a repo with blobs and trees but no commits, but you'd have to try even harder to get there. These are the absolute safest methods, if your script is scary.