Question:
How to edit a bad commit message in Git? Can you cite examples?
Answer:
There are 3 different situations, which are getting more and more complex:
-
Edit last local commit – BEFORE PUSH :
Thegit commit --amend
will open your editor, with the content of the message of the last commit and you can edit with ease. -
Edit older commits – BEFORE PUSH :
You will need to rebase your history, which is more complex than the previous process:$ git rebase -i HEAD~3 # Mostra a lista dos 3 últimos commits
The list will look something like this:
pick e499d89 Delete CNAME pick 0c39034 Better README pick f7fde4a Change the commit message but push the same commit. # Rebase 9fdb3bd..f7fde4a onto 9fdb3bd # # Commands: # p, pick = use commit # r, reword = use commit, but edit the commit message # e, edit = use commit, but stop for amending # s, squash = use commit, but meld into previous commit # f, fixup = like "squash", but discard this commit's log message # x, exec = run command (the rest of the line) using shell # # These lines can be re-ordered; they are executed from top to bottom. # # If you remove a line here THAT COMMIT WILL BE LOST. # # However, if you remove everything, the rebase will be aborted. # # Note that empty commits are commented out
Change
pick
toreword
on the commits you want to edit the message:pick e499d89 Delete CNAME reword 0c39034 Better README reword f7fde4a Change the commit message but push the same commit.
Save and close the file. After that git will open each of the
reword
-tagged commits for editing. Edit messages, save and close. -
Change commits AFTER PUSH
First of all, this is highly not recommended .
This can break the repository and be a lot of work.
99.9% of the time it's better to leave the commit wrong.To change the history after the push, just follow one of the steps above and then run:
git push --force
Sources:
1. git documentation
2. Github Guide – in English