git checkout -b <branchname1> <remote>/<branchname2>

Clone a remote branch and switch to it

This command is useful for starting work on a branch that exists on a remote by creating a new local branch named <branchname1> based on <remote>/<branchname2> and checking it out immediately.

The checkout operation moves HEAD to the target branch, the -b flag tells Git to create the branch, <branchname1> defines its name, and <remote>/<branchname2> sets the upstream reference so the new branch tracks that remote branch for future pulls and pushes.

Variations include using git checkout -b feature/foo origin/bar for a quick creation and checkout, adding --track with git checkout --track -b feature/foo origin/bar to explicitly set up tracking, using the newer command git switch -c feature/foo origin/bar for the same effect, or splitting steps with git branch feature/foo origin/bar followed by git checkout feature/foo.

Other related commands are git branch --track feature/foo origin/bar to only create and track, and git fetch before branch creation to update remote refs.

Examples:

  • git checkout -b feature/login origin/main
  • git checkout -b bugfix/123 upstream/develop
Related commands

Welcome to GitExamples!

Sign in to enable bookmarking, reminders, progress-tracking and more...