How to Reset the Local Branch to One in Remote Repository in Git
This tutorial will show how to reset a local branch in the local repository in git to be like the branch on the remote repository. Optionally, we can discard any untracked changes in the local repository.
Typically, we have a local branch with some changes that are no longer required or out of date. Also, we need to fetch the changes that are in the remote repository.
It usually happens when we are working in a collaborative environment; and some other team member has done some changes (fixes, feature development, etc.) and pushed those into the remote branch (ex. master
).
Thus, we need to do a reset of the local branch in the local repository and synchronize with the one in the remote repository.
We will now illustrate this with an example.
Using git reset
to Reset the Local Branch to One in Remote Repository
We typically have a local branch viz. master
used to track the remote branch with the same name in the remote repository.
We now will do a checkout
to the local branch viz. master
, if we are not already in it. Additionally, git checkout
removes the untracked files.
$ git checkout master
We will run the following command to reset the local branch viz. master
, to the remote repository.
$ git fetch origin
$ git reset --hard origin/master
The first command, get fetch
, downloads the objects and refs from origin
; the origin
is an alias created by git for the remote URL of the remote repository.
The second command, get reset
, reset the current HEAD
to the one on the remote branch. Please note, this will remove all the local changes.
All the changes/commits we have in the remote branch in the remote repository are present in the local branch of the local repository.
Optionally, we can also clean up the untracked changes by executing the following command.
$ git clean -xdf
Related Article - Git Reset
- Difference Between the Git Reset, Revert, and Checkout Commands
- How to Make the Development Branch Identical to the Master Branch
- How to Remove Local Git Changes
- How to Revert a Git Merge With Conflicts
- Difference Between Git RM --Cached and Git Reset File
- How to Revert a Git Repository by Commit ID