Some commonly used Git commands related to branch operations.

Create a new branch (locally and remotely)

create branch locally

We can use the following command to create a new branch

git branch <new_branch>

At this time, we are still in original branch. To switch to new branch, use the following command:

git checkout <new_branch>

The two steps can be combined with the following command:

git checkout -b <new_branch>

create branch remotely

To create a remote branch, use the following command:

git push -u origin <local_branch>

show branches

  • show all branches (local and remote): git branch -a
  • show all local branches: git branch -l
  • show all remote branches: git branch -r

Delete a branch

  • Delete local branch: git branch -d <branch_name>
  • Delete remote branch: git push -d <remote_name> <remote_branch>

Note that to delete a local branch, you need first to checkout to another branch.

Create a local branch from a remote branch?

First, we need to fetch the remote changes:

git fetch

Then we need to create a local branch from the remote branch:

git checkout -b local_branch_name remote_name/remote_branch