3

I pushed about 200 commits to the branch master.

On another server the branch A is checked out, but I need to checkout master here.

I could execute git checkout master and then immediately git pull.

But then a old state is going live until git pull is executed to update the branch.


Can I update a branch first and then check it out?

Black
  • 18,150
  • 39
  • 158
  • 271
  • `But then a old state is going live first until git pull was executed.` <--- can you explain what this exactly means? – Tim Biegeleisen Apr 05 '19 at 10:37
  • @TimBiegeleisen, if I checkout `B` then it is 200 commits behind ofc, so an old state will be checked out and being live. Not sure what you mean by cryptic. – Black Apr 05 '19 at 10:39
  • You can `git fetch` and update `origin/master` while on another branch. But, to update the local `master` branch, you'd have to checkout `master`, and I don't know any way to avoid this. – Tim Biegeleisen Apr 05 '19 at 10:43
  • @kapsiR, I don't understand how my question is a duplicate from the one you linked, can you explain? – Black Apr 05 '19 at 10:52
  • @Black As of my understanding, your question is about changing the branch without modifying the working tree (checkout master without changing the actual working tree). The working tree should only change after pulling? – kapsiR Apr 05 '19 at 10:55
  • @kapsiR no thats incorrect, I just try to update a branch before checking it out as my title says. – Black Apr 05 '19 at 11:00
  • 1
    @Black Ok. I deleted the possible dup. comment. Thanks for clarification – kapsiR Apr 05 '19 at 11:01

2 Answers2

4

After running git fetch, you can force master to change to where origin/master is:

git branch -f master origin/master

Then you can check it out:

git checkout master

Which will be at the state of origin/master and you will not pass by the intermediate state it was before.

Here is a brief example (I am checked out on test and change master to the same place as test):

> git log --graph --oneline
* d97b1f8  (HEAD -> test) - tata (1 second ago)
* e680fb5  - toto (9 seconds ago)
* 4515586  (master) - bar (24 seconds ago)
* e241705  - foo (28 seconds ago)

> git branch -f master test

> git log --graph --oneline
* d97b1f8  (HEAD -> test, master) - tata (9 seconds ago)
* e680fb5  - toto (17 seconds ago)
* 4515586  - bar (32 seconds ago)
* e241705  - foo (36 seconds ago)
Black
  • 18,150
  • 39
  • 158
  • 271
padawin
  • 4,230
  • 15
  • 19
1
git fetch origin master:master
git checkout master

Source: 1177 upticks at last count Merge, update, and pull Git branches without using checkouts

Alex
  • 11
  • 1