What is the difference between "git branch" and "git checkout -b"?

I used git checkout -b to create a new branch. I think that git branch does the same thing. How do these two commands differ, if they differ at all?


Solution 1:

git checkout -b BRANCH_NAME creates a new branch and checks out the new branch while git branch BRANCH_NAME creates a new branch but leaves you on the same branch.

In other words git checkout -b BRANCH_NAME does the following for you.

git branch BRANCH_NAME    # create a new branch
git switch BRANCH_NAME    # then switch to the new branch

Solution 2:

git branch creates the branch but you remain in the current branch that you have checked out.

git checkout -b creates a branch and checks it out.

It could be considered a short form of:

git branch name
git checkout name

Solution 3:

  • git branch: Shows all your branches
  • git branch newbranch: Creates a new branch
  • git checkout -b newbranch: Creates a new branch and switches to that branch immediately. This is the same as git branch newbranch followed by git checkout newbranch.