4

I often need to checkout latest version of another branch:

git checkout anotherbranch
git pull

How can I do that without checking out outdated version of anotherbranch first?

e.g.:

GIVEN

  1. There are branches master and feature1
  2. each branch has one remote called origin and equally named remote branch.
  3. there are no local unpushed commits

WHEN:

  1. I'm on feature1, and somebody merged PR into master

THEN:

How do I checkout latest version of master?

Does following the trick?

git fetch origin master
git checkout master
Liero
  • 25,216
  • 29
  • 151
  • 297
  • Does this answer your question? [Git pull without checkout?](https://stackoverflow.com/questions/18857570/git-pull-without-checkout) – Adam Sep 08 '21 at 10:25
  • @Adam The accepted answer to that question is in turn just a link to https://stackoverflow.com/questions/3216360/merge-update-and-pull-git-branches-without-using-checkouts, so that would probably be a better duplicate target. – IMSoP Sep 08 '21 at 13:08

2 Answers2

2

One way I deal with this general situation is to work with the remote tracking branch origin/master, rather than working with the local master branch. Let's say that you wanted to merge the latest remote master into feature1 from the feature1 branch. You could achieve that by using:

# from feature1
git fetch origin
git merge origin/master

The git fetch trick above will update all of your remote tracking branches, such that the local origin/master will now reflect whatever latest changes are on the Git repository. You can then use origin/master for whatever purpose you might have.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

How can I do that without checking out outdated version of anotherbranch first?

git fetch origin anotherbranch:anotherbranch
git checkout anotherbranch

How do I checkout latest version of master?

git fetch origin master:master
git checkout master
Adam
  • 4,180
  • 2
  • 27
  • 31
  • 2
    what if I do `git fetch origin master` instead `git fetch origin master:master`? – Liero Sep 08 '21 at 13:03
  • 2
    It would be good to explain what the magic "x:x" notation is doing here. I'm guessing it's deliberate, and different from just "git fetch origin anotherbranch" in some way? – IMSoP Sep 08 '21 at 13:05
  • `git fetch :` tells Git to fetch the remote branch and then create or update the local branch to point to the same commit. So far so expected. But: this command is safe in the sense that it will fail if the local branch exists and the update is not a fast-forward. Accidental merges and resets are avoided. (taken from the edit history of this post) – Torge Rosendahl Oct 29 '22 at 15:32