Data report"State of code review 2024" is now liveRead the full report

How to get the current branch name in Git

Kenny DuMez
Kenny DuMez
Graphite software engineer


Note

This guide explains this concept in vanilla Git. For Graphite documentation, see our CLI docs.


Understanding how to retrieve the current branch name in Git is important for developers, especially when working across multiple branches or collaborating in team environments. This guide will cover several methods to determine your active branch, helping you manage your repository more effectively.

  1. Using git branch

    The git branch command lists all the branches in your repository and highlights the current branch with an asterisk:

    Terminal
    $ git branch
    * main
    feature-x
    bugfix-y

    In this output, the current branch is main.

  2. Using git status

    git status provides a summary of the current state of your working directory, including the branch you are on:

    Terminal
    $ git status
    On branch main
    Your branch is up to date with 'origin/main'.
    nothing to commit, working tree clean

    This command not only shows that you are on the main branch but also confirms that your branch is synced with the remote repository.

  3. Using git rev-parse

    For a more script-friendly option, git rev-parse can be used to directly output the current branch name:

    Terminal
    $ git rev-parse --abbrev-ref HEAD
    main

    This command is particularly useful in scripts where you need to automate Git operations based on the current branch.

Creating an alias in Git can save time and reduce the amount of typing required for frequent commands like checking the current branch. You can set up an alias like this:

  1. Edit your Git configuration file:

    Open your global Git configuration file in a text editor:

    Terminal
    $ git config --global -e
  2. Add the alias under the [alias] section:

    You can add an alias named cb (current branch) to quickly get the name of the current branch:

    Terminal
    [alias]
    cb = rev-parse --abbrev-ref HEAD
  3. Use the alias:

    Now, you can simply type git cb to get the current branch name:

    Terminal
    $ git cb
    main

For more information on commands like git rev-parse see the official Git documentation.

Graphite
Git stacked on GitHub

Stacked pull requests are easier to read, easier to write, and easier to manage.
Teams that stack ship better software, faster.

Or install our CLI.
Product Screenshot 1
Product Screenshot 2