How to Reset the Local Branch to One in Remote Repository in Git

Azhar Bashir Khan Feb 02, 2024
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