How To Overwrite Local branch with Remote In Git

How To Overwrite Local branch with Remote In Git

Git is one of the most popular version control systems out there. It is free and open-source and allows you to do a number of complex actions to streamline your workflow in order to create an easy-to-collaborate-on project.

One of the most common issues that people face when trying to get started with git is to keep their local and remote branches in sync. A situation might arise where you want to completely overwrite your local branch with remote versions. The steps outlined below will help you keep your git workflow running smoothly so that you can avoid all those pesky conflict errors.

Related: Rename Git Branches

How To Rename A Git Branch: Local & Remote
In this guide, we will cover the basics of how to rename your local and remote git branches. Read on!

Method #1: Hard Reset Local Branch

1: Make sure to checkout to the branch you want to override

$ git checkout -b your-branch

2: Once you're on your branch, you can use the following command to overwrite your existing one.

$ git reset --hard @{u}

@{u} is shorthand for the upstream branch that your current branch is tracking. This is great if you don't remember the name of your remote branch and want to make sure that you're resetting to the current branch. For example, if you are on branch your-branch which is set up to track the remote origin/your-branch, @{u} will be the equivalent of your remote branch.

Alternatively, you could also reset to a specific branch by using the following command:

$ git reset --hard origin/your-branch

Method #2: Delete & Rebuild Your Local Branch

Another way to overwrite a branch is to delete its remote copy entirely and then fetch the remote origin.

1: The first step is to delete your local branch:

$ git branch -D local_branch

2: Next, fetch the latest copy of your remote branch from the origin

$ git fetch origin remote_branch

3: Lastly, you can now rebuild your local branch based on the remote branch you have just fetched

$ git checkout -b local_branch origin/remote_branch

And that's all folks, if you've followed these steps correctly, you should have a clean branch that is completely synced with your remote origin.