Git amend/reword (without adding/changing files)

2019-02-18 09:59发布

问题:

Often I want to edit a commit message without having to re-select the file-set from the last commit.

git commit file1.c file2.c

Accidental typo in commit message.

git commit file1.c file2.c --amend

This works, but Id like not to have to re-select the file-set from the original commit, I once accidentally did git commit -a --amend and added many changes unintentionally.

I know about git rebase -i HEAD~1 then replace pick with with r (re-word), but this ends up being a few steps.

Is there a way to re-word the last commit in one step without including any new files?

回答1:

Amending message without staged changes

As long as you don't have any changes staged in your staging area, you can simply use

git commit --amend

to edit your previous commit's message1.

Amending message even with staged changes

However, if you do have changes staged, then you can use the --only (or -o) flag in combination with --amend to only edit the message of the previous commit, without committing staged changes:

git commit --amend --only
git commit --amend -o # Shorter

This option was pointed out by David Ongaro in his answer.

Documentation

As stated in the git commit documentation (emphasis mine):

-o
--only  

Make a commit only from the paths specified on the command line, disregarding any contents that have been staged so far. This is the default mode of operation of git commit if any paths are given on the command line, in which case this option can be omitted. If this option is specified together with --amend, then no paths need to be specified, which can be used to amend the last commit without committing changes that have already been staged.

1As mentioned by Minitech and others.



回答2:

Just use git commit --amend without any other arguments. It will open up the editor and you can change your commit message.



回答3:

You can do git commit --amend -m <new commit message>. Of course, the precaution is to ensure that there are no staged changes as mentioned in other answers.