git,

Git: update commit before and after push

Nov 09, 2022 · 1 min read · Post a comment

Updating commits whenever before or after push goes against the Git religion and I consider it as an anti-pattern. And, since we are people, and we make mistakes, we don’t want to embarrass ourselves with some lame commit message such as “update”. If you want to learn more: The right way to write Git commit messages. However, as far as updating commits, here are few commands that could make your day better.

Prerequisites

  • Git

Solution

commit not pushed yet

To update the latest one, run:

git commit --amend -m "Updated something"

If you wish not to update the commit message, execute:

git commit --amend --no-edit

Now, push to remote:

git push -f origin <some_branch>

commit pushed to remote

In case the commit is pushed to remote, first make sure to “amend” your commit locally as the steps described above, and then run:

git push -f remote <some_branch>

Note(s): If you are not sure about forcefully destroying any updates made by anyone else in the meantime, a much secure alternative would be to replace -f (--force) with --force-with-lease. At least that’s the GitHub recommendation.

updating N commit messages

Step 1. Checkout the branch / commit that needs to be updated.

Step 2. Run the following command to list the last, let’s say 5 commits:

git rebase -i HEAD~5

Related: Git: restore vs reset vs revert vs rebase.

Step 3. Replace pick with reword, save and close the file.

Step 4. Update the commit message for each commit file.

Step 5. When ready, run:

git push -f origin <some_branch>

Conclusion

To find more neat Git commands and hacks, simply browse the Git category. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.

git