Made a typo in your commit message? Or forgot to mention an important detail in the message? Correcting a commit message in Git can be very easy - if it's the very last commit you want to edit!
Amending the Last Commit
To change the last commit, you can simply commit again, using the --amend flag:
$ git commit --amend -m "New and correct message"
Simply put, this overwrites your last commit with a new one. This also means that you're not limited to just editing the commit's message: you could also add another couple of changes you forgot.
$ git add another/changed/file.txt
$ git commit --amend -m "message"
However, keep two important details in mind:
- Amend only works with the very last commit. If you notice your mistake only after adding another commit, amend won't help you much.
- Amend rewrites the commit history in your repository: the old commit is replaced by a completely new one (a new and different commit object). This makes it very important that you don't amend (= rewrite) commits that you've already publishedto a remote repository! Because in that case, your colleagues might have already based their work on this commit - which you would try to replace using "amend".
Therefore, use "amend" whenever you want to change / edit your very last and unpushed commit.
hanging Older Commits
If you want to change older commits, Git also has a tool for this use case:
$ git rebase --interactive
The "interactive rebase" command, however, is quite an advanced tool: very powerful and quite dangerous. You should definitely understand what you're doing before applying it! See here if you really need to use it.
The mode of action, however, is the same as with the --amend flag: you are rewriting history! Therefore, just as with amend, you should not use interactive rebasing on commits you have already pushed!
0 comments:
Post a Comment