30

How do I create a new branch in git to begin work on a new feature?

I want the new branch to be a duplicate of the current branch (ie, the new branch's HEAD should be the same as the current HEAD).


Question differentiation:

3
  • 3
    Reopen queue reviewers: you may wish to read the meta.so discussion of this question here.
    – Tom Hale
    Sep 1, 2018 at 10:15
  • (Nitpick) I think you're having the wrong links for the "question differentiation" section. There are 4 links but only 2 questions.
    – user202729
    Sep 1, 2018 at 16:32
  • @user202729 The bottom two links were initially marked as duplicates as mentioned in the meta discussion linked in my previous comment. I'll edit the differentiation to make that more obvious.
    – Tom Hale
    Sep 2, 2018 at 4:43

2 Answers 2

49

TL;DR:

To create and start work on a new branch called FEATURE, you do:

git checkout -b FEATURE

Detailed explanation

To create a branch called FEATURE:

git branch FEATURE

However, this does not change your current branch.

You can then checkout the newly created branch (which means make to it the branch you're currently working on:

git checkout FEATURE

(You can see the current branch marked with a * in the output of git branch --list.)

Generally you want to start working in the branch you have just created, so the shortcut equivalent for both commands is git checkout -b FEATURE, which creates a new branch, then does checkout on it.

0
41

If you say

$ git checkout -b myFeatureBranch anotherBranch

It'll create myFeatureBranch off of anotherBranch. But if you say

$ git checkout -b myFeatureBranch

It'll create myFeatureBranch off of the current branch.

3
  • 1
    and how do we push this new branch to the remote repository
    – Mustafa
    May 31, 2022 at 22:57
  • 4
    In my opinion, this answer was clearer than the accepted one - kudos to @doctorram
    – AJM
    Jul 19, 2022 at 16:47
  • 1
    @mustafa In case somebody needs a quick reference if you have a remote called origin "git push -u origin myFeatureBranch".
    – Agricola
    Sep 1, 2023 at 19:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.