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

这可能吗?


当前回答

从命令行使用Git和Bash,你可以做到以下几点:

git commit -m "this is
> a line
> with new lines
> maybe"

当你想要新的一行时,只需输入并按Enter,“>”符号意味着你已经按了Enter,并且有一个新的行。其他答案也适用。

其他回答

遗憾的是,git似乎不允许在其消息中出现任何换行符。上面已经有各种合理的解决方案,但在编写脚本时,这些都很烦人。这里文档也可以工作,但是处理起来可能有点麻烦(比如yaml文件)

以下是我所做的:

git commit \
    --message "Subject" \
    --message "First line$(echo)Second line$(echo)Third Line"

虽然这仍然很难看,但它允许“一行程序”,这可能仍然有用。由于字符串通常是变量或与变量组合在一起,因此可以将丑陋的字符串保持到最小。

比如

git commit -m"test\ntest"

这并不奏效,但就像

git commit -m"$(echo -e "test\ntest")"

有用,但不是很漂亮。你在PATH中设置了一个git- commitb命令,它是这样做的:

#!/bin/bash

message=$1

git commit -m"$(echo -e "$message")"

像这样使用它:

git commitlb "line1\nline2\nline3"

提醒一下,我感觉一般惯例是第一行是摘要行,然后是两个换行符,然后是提交消息中的扩展消息,所以这样做会打破惯例。你当然可以:

git commitlb "line1\n\nline2\nline3"

在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的示例:

导致这个提交:

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

git commit -m 'Message

goes
here'

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

git commit -F- <<EOF
Message

goes
here
EOF

没有必要把事情复杂化。在-m "文本之后…下一行是通过按Enter得到的。当按下回车键时,出现>。当你完成后,只需输入“”并按Enter:

$ git commit -m "Another way of demonstrating multicommit messages:
>
> This is a new line written
> This is another new line written
> This one is really awesome too and we can continue doing so till ..."

$ git log -1
commit 5474e383f2eda610be6211d8697ed1503400ee42 (HEAD -> test2)
Author: ************** <*********@gmail.com>
Date:   Mon Oct 9 13:30:26 2017 +0200

Another way of demonstrating multicommit messages:

This is a new line written
This is another new line written
This one is really awesome too and we can continue doing so till ...

(编辑05-05-2021)

对于Windows用户,请使用GitBash For Windows。内置的Windows cmd不适用此方法。