Skip to main content

Git Branch

A branch is a version of the repository that diverges from the main working project. It is a feature available in most modern version control systems. A Git project can have more than one branch. These branches are a pointer to a snapshot of your changes. When you want to add a new feature or fix a bug, you spawn a new branch to summarize your changes. So, it is complex to merge the unstable code with the main code base and also facilitates you to clean up your future history before merging with the main branch.

Branches are the heart of Git. From the time of creating the repository until its deletion, everything will involve branches. We can perform various operations on Git branches.

The git branch command allows you to create, list, rename and delete branches. Many operations on branches are applied by git checkout and git merge commands. So, the git branch is tightly integrated with the git checkout and git merge commands.

Git Branch Syntax:

git branch <branch-name>

Git Branch Common Usage


  • git branch: List all of the branches in your repository. This is synonymous with git branch --list.

    Example:

    git branch

    Output:

      dev
    * master


  • git branch <branch-name>: Create a new branch called <branch-name>.

    Example:

    git branch dev


  • git branch -d <branch>: Delete the specified branch. This is a “safe” operation in that Git prevents you from deleting the branch if it has unmerged changes.

    Example:

    git branch -d dev


  • git branch -D <branch>: Force delete the specified branch, even if it has unmerged changes. This is the command to use if you want to permanently throw away all of the commits associated with a particular line of development.

    Example:

    git branch -D dev


  • git branch -m <old-branch> <new-branch>: Rename the branch.

    Example:

    git branch -m dev Branch1


  • git branch -a: List all remote branches.

    Example:

    git branch -a

    Output:

      dev
    * master
    remotes/gitopia-objects-store/master
    remotes/origin/master

You can learn more about the git branch command and its options in git-scm's documentation.