4 ways to create a Git branch quickly by example

The ability to create branches and perform risk-free development in an isolated programming space is one of Git’s greatest gifts to the programming world. But how do you create a Git branch?

Git branch create commands

The four commonly used commands to create a Git branch are:

  1. git branch <branchname>
  2. git checkout -b <branchname>
  3. git branch <branchname> <tag>
  4. git branch <branchname> <commit id>

Simple Git branch creation

The easiest way to create a Git branch is to use the branch switch and provide a branch name. The only shortcoming of this approach is that you are not moved into the branch you just created, so a subsequent checkout is required.

git branch alpha-branch
git checkout alpha branch

Git branch create and checkout

To avoid the need to run the checkout command after branch creation, you can simply use Git’s checkout switch with the -b flag. The following command will create a Git branch named beta-branch and switch you into the new branch at the same time.

git checkout -b beta

The use of the git checkout approach is the most common way developers create new Git branches.

create git branch

How to create Git branches from commits, tags and even the current branch.

Create a branch from a Git tag

Sometimes a developer wants to create a branch from a commit that has been tagged as milestone or release. To do that, simply use the git branch switch and provide the tag name after the new of the new branch to create. The following command will create a new Git branch off the M1 tag named charlie-branch:

git branch charlie-branch M1

Create a Git branch from a commit

Similarly, a developer can create a new Git branch from a commit. To do so, use the branch switch and provide the commit id after branch name. The following command creates a new Git branch off the commit with id 4596115:

git branch devo-branch 459615

Git branch listings

From time to time, it’s a good idea to take stock of all the Git branches you have created. Proper development housekeeping means you should prune your workspace from time to time and delete Git branches that are no longer needed. To list branches, just use the -a or –all options:

git branch -a

And to find out which branch you are currently on, a quick git status command will fit the bill:

git status

The gift of lightweight branch creation and branch deletion is one of the primary benefits developers enjoy when they switch from traditional version control systems to Git. Never be afraid to create a new Git branch and experiment. If your experiments fail, you can just delete the branch. And if they succeed, you’re just a git merge and push away from showing all of your fellow developers how brilliant you are.

App Architecture
Software Quality
Cloud Computing
Security
SearchAWS
Close