选择应该提交哪些行进行提交

假设你在一个或多个文件中有许多更改,但是从每个文件中你只想提交一些更改,你可以使用以下命令选择所需的更改:

git add -p

要么

git add -p [file]

你的每项更改都将单独显示,每次更改时,系统都会提示你选择以下选项之一:

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.

这将暂存你选择的文件的各个部分。然后你可以像这样提交所有阶段性的更改:

git commit -m 'Commit Message'

未暂存或提交的更改仍将显示在你的工作文件中,如果需要,可以在以后提交。或者如果剩余的更改是不需要的,可以将它们丢弃:

git reset --hard

除了将较大的更改分解为较小的提交之外,此方法对于查看你要提交的内容也很有用。通过单独确认每个更改,你有机会检查你编写的内容,并可以避免意外地暂存不需要的代码,如 println / logging 语句。