How to commit one file at a time using Git?
Say there are several files modified and I just want o开发者_运维技巧ne files committed each time. How to do that? Given an example with status looks like below. Thanks!!
Ex:
> git status
# modified: file01.txt
# modified: file02.txt
# modified: file03.txt
# modified: file04.txt
# modified: file05.txt
Use git add -p
followed by git commit
. git add -p
asks you for each change whether to stage it for committing, which is super convenient.
You can also use -p
with git reset
and git checkout
.
There are a few ways, but the simplest is probably:
git commit file01.txt
git commit file02.txt
...
Any paths you list after the commit command will be committed regardless of whether they're staged to be committed. Alternatively, you can stage each one, and then commit:
git add file01.txt
git commit
git add file02.txt
git commit
...
git add -p
described by daf's answer is nice, but for a more direct approach to picking and choosing, I'm really liking:
git add -e
It generates the appropriate patch, then loads it up in your preferred editor so that you can edit it as desired. When you save the file and exit the editor, and only the changes made by your edited version of the patch are added to the index.
If you accidentally close the editor without making changes, you'll probably want to use get reset HEAD
and then start over.
git add file01.txt
git stash
git commit -m'commit message'
git stash pop
repeat.
On the subject of staging partial changes within a file, it's worth noting that various text editors have support for doing this in a nicer way than any of the command-line options.
I use Magit for Emacs, which uses single keystrokes for stepping forward or backwards through the hunks, increasing or decreasing the granularity, and staging or un-staging the current hunk. You can also mark a region manually and stage (or un-stage) just that region.
I believe there are similar plugins for vim, and other editors / IDEs as well.
精彩评论