Introduction
🧑💻 New to Git or LabEx? We recommend starting with the Quick Start with Git course.
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.
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.