Git

How to Get Current Branch in Git

Git is a decentralized system that is used among developers to track the team project. We typically deal with branches when we work on a Git local and remote repository. These branches represent a self-dependent line of development and work as an abstraction for editing, staging, and commit processes. It saves as a reference to committing in Git, and you can check the name of a current branch at any stage.

This study will explore the methods to get the current branch in Git.

How to Get Current Branch in Git?

We can get the current branch in Git using different commands, such as:

    • git branch
    • git rev-parse
    • git symbolic-ref

Let’s execute the above commands one by one to check the current working branch!

First, open up “Git Bash” on your system with the help of the “Startup” menu:


Move to the specific Git directory by running the “cd” command with the Git directory folder path:

$ cd "C:\Users\nazma\clone_tag\tag"

 

Method 1: Get Current Branch in Git Using “git branch” Command

Execute the “git branch” command without any options displays all branches of the local directory and add an asterisk “*” symbol with the current branch:

$ git branch

 
As you can see, in the below-given output our current branch name is “feature”:


If we run the “git branch” with the option “-a”, it will return all existing remote and local branches as well as specifying the current branch:

$ git branch -a

 

Alternatively, you can utilize another option “–show-current” in the same command to only display the current branch:

$ git branch --show-current

 

Method 2: Get Current Branch in Git Using “git rev-parse” Command

There is another way of retrieving the current branch name which is using “git rev-parse” command with “–abbrev-ref”:

$ git rev-parse --abbrev-ref HEAD

 

Method 3: Get Current Branch in Git Using “git symbolic-ref” Command

To display the current branch name, “git symbolic-ref” command can also be used. This command shows the short symbolic reference to the working branch HEAD:

$ git symbolic-ref --short HEAD

 
As you can see, we have successfully retrieved the current branch in Git:


That’s all! We have explored the simple and efficient way of getting the current working branch in Git.

Conclusion

To get the name of the current branch in Git, there are different commands with multiple options, such as “$ git branch” and “$ git branch -a”, which will display all local and remote repository branches, distinguish the current working branch with asterisk “*” symbol. The git command “git rev-parse” and “git symbolic-ref” are also used to get the current branch name on Git Bash. This study demonstrated the method to get the current branch in Git.

About the author

Maria Naz

I hold a master's degree in computer science. I am passionate about my work, exploring new technologies, learning programming languages, and I love to share my knowledge with the world.