我正在从命令行使用Git,并试图在提交消息中添加换行符(使用Git commit -m "")而不进入Vim。

这可能吗?


当前回答

下面是在Windows上使用标准cmd.exe shell的失败解决方案列表(为您节省一些试错时间!):

git commit -m 'Hello Enter不起作用:它不会要求新的行 git commit -m "Hello输入idem git commit -m "Hello^输入idem git commit -m 'Hello^ Enter World'看起来很正常,因为它会问"More?",并允许写新的一行,但最后当执行git log时,你会看到它仍然是一行消息…

TL;DR:即使在Windows上,命令行解析的工作方式不同,^允许多行输入,在这里也没有帮助。

最后,git commit -e可能是最好的选择。

其他回答

当然,它是如何完成的取决于您的shell。在Bash中,可以在消息周围使用单引号,也可以只打开引号,这将使Bash提示另一行,直到关闭引号。是这样的:

git commit -m 'Message

goes
here'

或者,你可以使用“here文档”(也称为heredoc):

git commit -F- <<EOF
Message

goes
here
EOF

你应该能够使用

git commit -m $'first line\nsecond line'

从Bash手册:

形式为$'string'的单词被特殊处理。这个词扩展为 属性指定的反斜杠转义字符替换为 ANSI C标准。

这包括如上所示的对换行符的支持,以及十六进制和Unicode代码等。转到链接部分查看反斜杠转义字符的列表。

在Git提交中添加换行符

尝试以下命令创建多行提交消息:

git commit -m "Demonstrate multi-line commit message in Powershell" -m "Add a title to your commit after -m enclosed in quotes,
then add the body of your comment after a second -m.
Press ENTER before closing the quotes to add a line break.
Repeat as needed.
Then close the quotes and hit ENTER twice to apply the commit."

然后验证你做了什么:

git log -1

你应该得到这样的结果:

截图来自我使用PowerShell和Poshgit创建的一个示例。

这适用于所有终端和操作系统AFAIK。

下面是bash的示例:

导致这个提交:

在Bash/Zsh中,你可以简单地在引号内使用文字换行:

git commit -m 'Multi-line
commit
message'

ANSI-C引用也适用于Bash/Zsh:

git commit -m $' multiline \ncommit\nmessage'

您还可以指示Git使用您选择的编辑器来编辑提交消息。来自git-commit的文档:

用于编辑提交日志消息的编辑器将从 GIT_EDITOR环境变量,核心。编辑器配置 变量、VISUAL环境变量或编辑器 环境变量(按此顺序)。详见git-var。

因此,使用nano编辑您的消息,例如,您可以运行:

export GIT_EDITOR=nano
git commit

如果你只是想要一个标题行和一个内容行,你可以使用:

git commit -m "My head line" -m "My content line."

注意,这会创建单独的段落,而不是行。所以在每两个-m行之间会有一个空行,例如:

My head line

My content line.