The way that Git recommends that committing be done is such that each change is an atomic, logical commit. In other words, it represents one logical change (executed well) and the entire testsuite passes both before and after the change.
One situation in which adding and committing may be done separately is when you're working on perfecting a commit. You may have an initial version of your code which works, but is messy or still has debugging code in it. You can add this change to the index using git add
while continuing to refine it in your work tree. If you find that you've broken things, you can roll back to the version in the index and try again. On the other hand, if you find that a change is better, you can add it again, until you're finally ready to commit.
Another, equally valid workflow for this situation is to make multiple commits, one each time the change is an improvement over the last, and then squash them together using git rebase -i
or git reset --soft
. Which you want to do depends on your preferred development style; they will essentially both produce the same result.
An alternative situation you may want to use git add
separately from git commit
is when you want to stash only some changes. You can use git add
to keep the changes you want in your working tree and then git stash --keep-index
to stash the rest of them away.
A question which you didn't ask but which might be on your mind is why the two functions are separate. This is because sometimes when developing you end up with changes from multiple logical commits in your tree and you want to commit only part of them at once, making additional commits for additional logical changes. Being able to add only part of the changes at once means you can commit those, and then add more changes and commit them, and so on.