Suppose you have many changes in one or more files but from each file you only want to commit some of the changes, you can select the desired changes using:
git add -p
or
git add -p [file]
Each of your changes will be displayed individually, and for each change you will be prompted to choose one of he following options:
y - Yes, add this hunk
n - No, don’t add this hunk
d - No, don’t add this hunk, or any other remaining hunks for this file.
Useful if you’ve already added what you want to, and want to skip over the rest.
s - Split the hunk into smaller hunks, if possible
e - Manually edit the hunk. This is probably the most powerful option.
It will open the hunk in a text editor and you can edit it as needed.
This will stage the parts of the files you choose. Then you can commit all the staged changes like this:
git commit -m 'Commit Message'
The changes that were not staged or committed will still appear in your working files, and can be committed later if required. Or if the remaining changes are unwanted, they can be discarded with:
git reset --hard
Apart from breaking up a big change into smaller commits, this approach is also useful for reviewing what you are about to commit. By individually confirming each change, you have an opportunity to check what you wrote, and can avoid accidentally staging unwanted code such as println/logging statements.