14

If

  • I have local repo with a remote $REMOTE already set up
  • and a new branch $BRANCH exists on the remote repo that I haven't fetched, yet

can I fetch that branch and check it out into a tracking local branch of the same name in a single command?

I can achieve the desired result in two commands either with

git fetch $REMOTE $BRANCH
git checkout $BRANCH # or more explicitly git checkout -b $BRANCH $REMOTE/$BRANCH

or (inspired by this answer to Question How do I check out a remote Git branch?) with

git fetch $REMOTE $BRANCH:$BRANCH
git branch --set-upstream-to=$BRANCH $BRANCH
das-g
  • 9,718
  • 4
  • 38
  • 80

1 Answers1

15

There is no builtin command, but you could define an alias in your ~/.gitconfig:

[alias]
  fetch-checkout = !sh -c 'git fetch $1 $2 && git checkout $2' -
das-g
  • 9,718
  • 4
  • 38
  • 80
knittl
  • 246,190
  • 53
  • 318
  • 364
  • @das-g: well, you could always do [`git checkout --track FETCH_HEAD`](https://git-scm.com/docs/git-checkout) or some variant of it – knittl Nov 05 '15 at 06:31
  • @das-g: I looked further into the topic, but I was unable to find a way to use `FETCH_HEAD` to create a tracking branch. Looks like you have to go with the alias – knittl Nov 06 '15 at 16:25
  • But it loose autocompletion. And I almost always use it beacuse I have easy-to-remember branches prefixes, but I can't remember its full name :( – Alex Zhukovskiy Oct 18 '17 at 14:50
  • You'd have to manually add this command to the bash autocompletion list (or whatever shell you are using). – knittl Oct 18 '17 at 16:43