The trick is to recognize that you are in complete control of which changes get staged. This might be all changes, it might be changes to one file, it might be some changes to some files. Basically, it can be whatever you want.
The interesting bit isn't really git commit
, but git add
. Here are some common secenarios:
Stage all changes to file foo.bar
:
git add foo.bar
Stage some changes from file foo.bar
:
git add --patch foo.bar
This mode will "chunk" your changes and ask if each chunk should be committed.
Stage all changes to tracked files (i.e. ones that Git is already tracking):
git add -u
The documentation for this option explains what it does better than I can:
Update the index just where it already has an entry matching <pathspec>
. This removes as well as modifies index entries to match the working tree, but adds no new files.
If no <pathspec>
is given when -u
option is used, all tracked files in the entire working tree are updated (old versions of Git used to limit the update to the current directory and its subdirectories).
Many people also like to use git add .
, but I've never made that part of my workflow. You can read about the differences between git add .
and git add -u
in this question. Basically, git add .
will also stage changes to untracked files, but does not stage file deletions, which -u
does stage.
Of course, you can also stage changes from multiple files together. I tend not to break commits up by file but rather by logical change. If you're fixing a bug and that requires modifications to three files, those three sets of modifications go together. git add foo bar baz
, git commit
.
It is very useful to review your staged changes before committing.
git diff
shows unstaged changes.
git diff --staged
shows staged changes. These are the ones that will be committed when you run git commit
.
I usually run both of these before committing, just to make sure that I know what I've got staged.
If you want to commit all modified files (ones that would be staged with git add -u
) you can use the shortcut git commit -a
:
by using the -a switch with the commit command to automatically "add" changes from all known files (i.e. all files that are already listed in the index) and to automatically "rm" files in the index that have been removed from the working tree, and then perform the actual commit;