如何从命令行提交具有“消息”和“描述”的更改?

618

我可以通过git(命令行而不是Mac应用程序)将提交推送到GitHub。

当我直接从GitHub Web界面推送提交时(例如:快速修复错别字),我有机会“评论”提交,并且GitHub会给我一个提交标题和一个提交描述。我发现这非常有用。

但是,当我从本地计算机git push时,git会打开我的默认编辑器:所以我写下提交的注释,然后GitHub自动将其分为标题和“正文”。是否有一种方法可以在终端中漂亮地注释提交?


这里有很好的描述:https://dev59.com/Im445IYBdhLWcg3wDWAP#46645586 - blongho
4个回答

1204

还有一种更直接、更清晰的方法

git commit -m "Title" -m "Description ..........";

65
这是一个不错的技巧,但我更喜欢下面给出的答案,因为它提供了一种轻松输入带有换行符的长描述的方法。原文链接:https://dev59.com/cWQo5IYBdhLWcg3wV-Qx#36427485。 - John Red
36
我也这么做 ^ 但是如果您在提交后不断地进行提交,您可能不想每次都打开VIM。你能否通过这种方式向描述中添加 \n?例如: `git commit -m“标题”-m“描述....\n新行....\n另一行”。 - James111
4
为什么不@James111 - zzlalani
5
在描述中添加\n以换行的方式并不起作用。请参考这个StackOverflow帖子 - Dhruv Saraswat
5
如果您要使用 \n,需要将其放在 $'' 内,就像这样:$'test\ntext' - PQCraft
显示剩余4条评论

598

不带任何标志使用git commit命令。配置的编辑器将打开(在本例中为Vim):

enter image description here

按下键盘上的INSERT键开始输入,然后在插入模式下创建更好的提交及其说明。例如:

enter image description here

完成所有需要的内容后,要返回到Git,首先应该退出插入模式,按ESC。现在通过在键盘上键入:wq(w - 写入,q - 退出)来保存更改并关闭Vim编辑器:

enter image description here

然后按ENTER

在GitHub上,此提交将如下所示:

enter image description here

您可以使用VS Code作为提交编辑器:

git config --global core.editor "code --wait"

从VS Code文档网站:VS Code作为Git编辑器

Gif演示:输入图像描述


我认为在保存您的提交时有一点变化,只需按下ctrl+x,它会提示您按y保存,然后按回车键,git push就可以完成工作了。 - Mahesh Jamdade
2
“without any flags” - 好吧,你确实可以使用一些标志,例如“--all”、“--no-verify”等等。(我还没有检查,但可能除了“-m”之外的所有标志都可以使用) - Mosh Feu

81
git commit -a -m "Your commit message here"

“will quickly commit all changes with the commit message. Git commit "title" and "description" (as you call them) are nothing more than just the first line, and the rest of the lines in the commit message, usually separated by a blank line, by convention. So using this command will just commit the "title" and no description.”
“If you want to commit a longer message, you can do that, but it depends on which shell you use.”
“In bash the quick way would be:”
git commit -a -m $'Commit title\n\nRest of commit message...'

13
使用 a 标记,git 会暂存所有修改过的文件,这通常不是所期望的。我建议从你的示例中删除 a 标记。 - Haris Muzaffar
@HarisMuzaffar 我不知道你怎么看,但这种行为在我的工作流程中是“通常期望的”,而且我正是因为这个答案才了解到这个标志。:P - DexieTheSheep

3

如果您在提交代码后想通过标题和正文来改进提交信息,您可以使用reword命令。这种方法更加有用,因为只有在编写完代码后,您才知道代码的作用。

git rebase -i origin/master

然后,您的提交将出现:
pick e152ce2 Update framework
pick ffcf91e Some magic
pick fa672e1 Update comments

选择您想要改写并保存的提交。
pick e152ce2 Update framework
reword ffcf91e Some magic
pick fa672e1 Update comments

现在,您有机会添加标题和正文,其中第一行将是标题。
Create perpetuum mobile

Redesign laws of physics with a pinch of imagination. Open a wormhole in 23 dimensions. Add protection to avoid high instability.

6
你的方法确实可行,但只适用于非常具体的情况。如果你已经推送了提交(除非有某种黑魔法:)),你不能这样做,更重要的是,它并不完全符合原帖描述的情况。 - Tin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接