How to Create a Git Branch in 6 Different ways


Example 1: Create a new branch

    Syntax:

    git branch <new-branch-name>

    This is the most common way a developer creates a new git branch using the console.

    Example:

    % git branch ticket-2023

    In this example a new branch with name ticket-2023 will be created from the current branch (main in this case) and will point to the same commit as the branch that you were on (main in our case) while executing the branch command.

    Git Branch Command Example 1


Example 2: Create a new branch and switch to it

    You can switch to the new branch using the command git checkout command.

    % git checkout ticket-2023
    
    Switched to branch 'ticket-2023'

    But if you want to create a new branch as well as switch to it immediately then make use of the -b flag.

    Syntax:

    git branch -b <branch-name>

    Example:

    % git -b branch ticket-2023-07
    
    Switched to a new branch 'ticket-2023-07'

    As you can see we were able to switch to the newly created branch immediately in one command.



Example 3: Create a new branch from an existing branch

    As we saw in Example 1 when we run the git branch command with just the new branch name, the new branch is created from the current branch you are on, but what if you want to create a new branch from a specific branch? In such a case you can pass in the from-branch-name as a parameter.

    Syntax:

    git branch <new-branch-name> <from-branch-name>

    Example:

    % git branch ticket-2023-08 ticket-2023-07


Example 4: Create a new branch from a commit

    Like the same way we created a branch from another branch, we can make use of the commit-hash as well to create a new branch.

    Syntax:

    git branch <new-branch-name> <commit-hash>

    Example:

     % git log --oneline                   
    216e7af (HEAD -> ticket-2023-07) some commit
    a348bd9 (ticket-2023-08, ticket-2023, main) init commit
    
    % git branch branch-new-123 a348bd9 


Example 5: Create a new branch from the remote origin branch

    If you do not have a branch locally or you want to create one from a remote git origin server (bitbucket, Github, Gitlab), you can do that as follows,

    Syntax:

    git branch <new-branch-name> <origin/remote-branch-name>

    Example:

    % git branch ticket-2025 origin/master


Example 6: Create a new branch using tags

    Syntax:

    git branch <new-branch-name> <tags/tag-name>

    Example:

    % git branch ticket-2026 tags/v.3.5


Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap