如何让 git 提交消息分成多行?

How can I make git commit messages divide into multiple lines?

当我使用 git log 查看我的提交说明时,我希望它看起来像这样:

1. what I changed
2. blank line
3. why I changed it

...像这样在 3 行而不是 1 行中:

1. what i changed  2. blank line 3. why i changed

但是,git log 显示在一行中。那么,如何使用 git commit -m 来实现这一点?

您只需使用以下命令:

$ git commit -m "1. what i changed
> 2. blank line
> 3. why i changed"

在您的终端中,只需按 'enter' 换行。在您添加结束引号之前,提交消息不会结束。 git 日志将如下所示:

$ git log
commit abcde2f660c707br2d20411581c4183170c3p0c2
Author: Alex Pan <alexpan@whosebug.com>
Date:   Tue Apr 28 20:52:44 2015 -0700

    1. what i changed
    2. blank line
    3. why i changed

您描述的多行格式是 Git 推荐的格式(参见 the documentation of git commit 中的讨论)。最简单的方法是使用 git commit 而不使用 -m,然后在文本编辑器中编写消息。

我发现将提交消息保存到文件中,然后使用 -F 选项更容易。

示例:

$ cat > /tmp/commit_msg.txt
DE123 bug fix: incorrect fetching of instance details
- fixed this and that
- also did such and such
$ git commit -F /tmp/commit_msg.txt

您也可以在提交前使用编辑器编辑消息文件。

在尝试以编程方式执行此操作时,您可以使用 stdin

而不是使用临时文件

git commit -F-

然后将消息写入标准输入

使用两个 --message/-m 选项,第一个用于主题,第二个用于正文。

文档摘录:

-m <msg>

--message=<msg>

Use the given as the commit message. If multiple -m options are given, their values are concatenated as separate paragraphs.

在您的情况下,它完全符合您的要求,在第一行和第二行之间插入一个空行。

git commit -m "Subject: what I changed" -m "Body: why I changed it"

如果您想修改之前添加的评论,这很有用。

我需要一个 bash 脚本为我做多行 git 提交,所以这里有两个我想出的选项:

  1. 写入临时文件,然后提交文件内容作为消息:

     printf "first line\nsecond line\nthird line" > "file.txt"
     git commit -F "file.txt"
    
  2. (我的首选方法):写入一个临时变量,然后将变量的内容作为消息提交。请注意,$MSG 周围的引号在执行任何命令以重新调用变量内容时 是必需的! 如果没有它们,您将失去你的换行符。

     MSG="$(printf "first line\nsecond line\nthird line")"
     git commit -m "$MSG"
    

作为第二种方法的扩展,如果您需要编写多段或多步构建消息的脚本,这也是可能的。不过要小心!请注意我放置换行符 (\n) 的位置。我不会将它们放在任何 printf 字符串的末尾。那是因为如果我这样做,他们会 get gobbled up,因为 bash 自动 删除任何 尾随 换行符 ,因为它很愚蠢那。所以,改为这样做,效果很好:

    MSG="$(printf "first line")"
    MSG="$(printf "${MSG}\nsecond line")"
    MSG="$(printf "${MSG}\nthird line")"
    git commit -m "$MSG"

来自上述任何 git commit 的示例 git log 输出:

commit e1983659c6ae2e9d2eb4332657329837582fc32b (HEAD -> master)
Author: Gabriel Staples <email@gmail.com>
Date:   Tue Mar 24 00:55:31 2020 -0700

    first line
    second line
    third line

参考文献:

  1. Unix & Linux: "Why does shell Command Substitution gobble up a trailing newline char?"
  2. 非常有用! ==> How can I have a newline in a string in sh? <==