Update Remote Branch After Rewriting History

GitGitBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

Git is a powerful version control system that allows developers to track changes made to their codebase. One of the key features of Git is the ability to rewrite history, which can be useful when you need to make changes to previous commits. However, rewriting history can cause issues when trying to push changes to a remote repository. In this lab, you will learn how to update a remote branch after rewriting history locally.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL git(("`Git`")) -.-> git/CollaborationandSharingGroup(["`Collaboration and Sharing`"]) git/CollaborationandSharingGroup -.-> git/remote("`Manage Remotes`") subgraph Lab Skills git/remote -.-> lab-12734{{"`Update Remote Branch After Rewriting History`"}} end

Update Remote Branch After Rewriting History

When you rewrite history locally, you create a new commit with a different SHA-1 hash. This means that the commit history on your local branch is different from the commit history on the remote branch. If you try to push your changes to the remote branch, Git will reject the push because it will see the commit history as diverged. To solve this problem, you need to force an update of the remote branch.

To complete this lab, you will use the Git repository git-playground from your GitHub account, which comes from a fork of https://github.com/labex-labs/git-playground.git.

  1. Clone the git-playground repository to your local machine:
git clone https://github.com/your-username/git-playground.git
  1. Update a commit with the message "Added file2.txt" to a commit with the message "Update file2.txt":
git commit --amend
  1. Push changes from local branch to remote repository:
git push
  1. If you can't push it successfully, please force push it:
git push -f origin master

The -f flag forces Git to update the remote branch with your changes, even though the commit history has diverged.

This is the final result:

commit b8c530558ecd004156dd05ac7d22d8cf07b2c28e (HEAD -> master, origin/master, origin/HEAD)
Author: Hang <huhuhang@users.noreply.github.com>
Date:   Wed Apr 26 14:16:25 2023 +0800

    Update file2.txt

commit cf80005e40a3c661eb212fcea5fad06f8283f08f
Author: Hang <huhuhang@users.noreply.github.com>
Date:   Wed Apr 26 14:16:25 2023 +0800

    Added file1.txt

commit b00b9374a7c549d1af111aa777fdcc868d8a2a01
Author: Hang <huhuhang@gmail.com>
Date:   Wed Apr 26 14:16:00 2023 +0800

    Initial commit

Summary

In this lab, you learned how to update a remote branch after rewriting history locally. By using the git push -f command, you can force Git to update the remote branch with your changes, even if the commit history has diverged. It is important to use this command with caution, as it can overwrite changes made by other developers.

Other Git Tutorials you may like