7

git commit can fail for reasons such as gpg.commitsign = true && gpg fails (for whatever reason). Retrying the command opens a blank editor; the message is lost.

When this happens, is there any way to recover the written commit message, to retry committing with the same message?

2 Answers 2

9

From man git-commit:

FILES
       $GIT_DIR/COMMIT_EDITMSG
           This file contains the commit message of a commit in progress. If git commit exits due to an error before creating a commit, any commit message that has been provided
           by the user (e.g., in an editor session) will be available in this file, but will be overwritten by the next invocation of git commit.

So, rather than repeat git commit, to retry with the previous message one can use:

$ git commit -m "$(cat .git/COMMIT_EDITMSG)"

Or in general (suitable for an alias for example):

$ git commit -m "$(cat "$(git rev-parse --git-dir)/COMMIT_EDITMSG)")"
2

To commit again with the same commit message as the previous (failed) commit:

git commit -F "$(git rev-parse --git-dir)/COMMIT_EDITMSG" 
  • To get a chance to edit the commit message in a text editor before committing, add the -e (--edit) option.
  • If the failed commit was a verbose commit (e.g. git commit --verbose), you might need to add --cleanup=strip so that the comments that Git added to the verbose commit will not be considered as part of the commit message.

Combined example — to edit the failed commit's message in a text editor and then let Git clean up the edited commit message right before committing:

git commit -eF "$(git rev-parse --git-dir)/COMMIT_EDITMSG" --cleanup=strip

References from man git-commit:

-F <file>, --file=<file>
    Take the commit message from the given file. Use - to read the
    message from the standard input.
-e, --edit
    The message taken from file with -F, command line with -m, and from
    commit object with -C are usually used as the commit log message
    unmodified. This option lets you further edit the message taken
    from these sources.
--cleanup=<mode>
    This option determines how the supplied commit message should be
    cleaned up before committing. The <mode> can be strip, whitespace,
    verbatim, scissors or default.

    strip
        Strip leading and trailing empty lines, trailing whitespace,
        commentary and collapse consecutive empty lines.
    ...
FILES
       $GIT_DIR/COMMIT_EDITMSG
           This file contains the commit message of a commit in progress. If
           git commit exits due to an error before creating a commit, any
           commit message that has been provided by the user (e.g., in an
           editor session) will be available in this file, but will be
           overwritten by the next invocation of git commit.

(Tested in git version 2.39.2)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .