Get the Current Branch Name

GitGitBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

When working with Git, it's important to know which branch you're currently on. This information can be useful when collaborating with others or when managing multiple branches in your own repository.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL git(("`Git`")) -.-> git/BranchManagementGroup(["`Branch Management`"]) git/BranchManagementGroup -.-> git/branch("`Handle Branches`") subgraph Lab Skills git/branch -.-> lab-12719{{"`Get the Current Branch Name`"}} end

Get the Current Branch Name

Write a command that prints the name of the current branch in a Git repository.

Suppose you're working on a project stored in the https://github.com/labex-labs/git-playground repository. You've made some changes to the README.md file and want to commit them to the current branch. However, before doing so, you want to make sure you're on the correct branch.

To check the current branch, you can use the following command:

git rev-parse --abbrev-ref HEAD

This will print the name of the current branch to the console. For example, if you're currently on the master branch, the output will be:

master

If you switch to a different branch, such as feature-branch, the output will change accordingly:

git checkout -b feature-branch
git rev-parse --abbrev-ref HEAD

This will output:

feature-branch

Summary

To print the name of the current branch in a Git repository, use the git rev-parse --abbrev-ref HEAD command. This can be useful when collaborating with others or when managing multiple branches in your own repository.

Other Git Tutorials you may like