Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a fresh copy of a branch from the remote repository?

Tags:

git

My friend's local master branch is apparently a disaster (through accidental merges and commits, I guess). However, his dev branches are fine but contain changes he's not ready to push to remote.

What's the best way of overriding his local master branch with the remote master branch and get a fresh copy (without overriding his other branches)?

like image 601
Brian Avatar asked Apr 14 '11 01:04

Brian


People also ask

How do you copy a branch from a remote repository?

You can clone a specific branch from a Git repository using the git clone –single-branch –branch command. This command retrieves all the files and metadata associated with one branch. To retrieve other branches, you'll need to fetch them later on.

How do I get all changes from a remote branch?

In order to fetch these changes from your remote, or in other words, download the changes to your local branch, you will perform a Git pull. Under the covers, a Git pull is actually a Git fetch followed by a Git merge. Git pull is just a shortcut to perform both of these actions in one step.


1 Answers

As Jefromi commented,

git checkout master git reset --hard origin/master 

does the right thing: setting the master to its origin state. (If you are already on the master branch, you can omit the first command.) It also leaves the branch's reflog intact.


Old inferior answer:

git checkout dev git branch -D master git checkout master 

This switches to another branch ("dev" in this case – choose any other branch you might have), deletes the local master branch, and then recreates it from remotes/origin/master (which might not work depending on your settings and Git version). The last command is often equivalent to

git checkout -b master remotes/origin/master 

Compared to the new answer above this has the disadvantage that the reflog is destroyed and recreated (i.e. you can't as easy undo this if needed), and it is less clear what happens here. Also, you need to have another branch existing to which you can switch during deletion and recreation (but that was the case in the original question).

like image 131
Paŭlo Ebermann Avatar answered Sep 29 '22 04:09

Paŭlo Ebermann