Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace local branch with remote branch entirely in Git?

Tags:

git

I have two branches:

  1. local branch (the one which I work with)
  2. remote branch (public, only well-tested commits go there)

Recently I seriously messed up my local branch.

How would I replace the local branch entirely with the remote one, so I can continue my work from where the remote branch is now?

I have already searched SO and checking out to the remote branch locally does not have any effect.

like image 398
YemSalat Avatar asked Feb 09 '12 11:02

YemSalat


People also ask

How do I overwrite local master with remote?

If you need to completely replace the history of your local master with your remote master (for example, if you've been playing with commits or rebase), you can do so by renaming your local master, and then creating a new master branch.

How do I overwrite a local branch?

Just like git push --force allows overwriting remote branches, git fetch --force (or git pull --force ) allows overwriting local branches. It is always used with source and destination branches mentioned as parameters.

How do I delete a local branch and pull remote branch?

Deleting a branch LOCALLY Delete a branch with git branch -d <branch> . The -d option will delete the branch only if it has already been pushed and merged with the remote branch. Use -D instead if you want to force the branch to be deleted, even if it hasn't been pushed or merged yet. The branch is now deleted locally.


2 Answers

  1. Make sure you've checked out the branch you're replacing (from Zoltán's comment).
  2. Assuming that master is the local branch you're replacing, and that "origin/master" is the remote branch you want to reset to:

    git reset --hard origin/master 

This updates your local HEAD branch to be the same revision as origin/master, and --hard will sync this change into the index and workspace as well.

like image 144
araqnid Avatar answered Sep 23 '22 09:09

araqnid


That's as easy as three steps:

  1. Delete your local branch: git branch -d local_branch

  2. Fetch the latest remote branch: git fetch origin remote_branch

  3. Rebuild the local branch based on the remote one:

    git checkout -b local_branch origin/remote_branch

like image 30
adamsmith Avatar answered Sep 21 '22 09:09

adamsmith