How to List Branches That Contain a Given Commit?

Better Stack Team
Updated on August 12, 2024

To list branches that contain a specific commit in Git, you can use the git branch command with certain options to search through your branches. Here’s a step-by-step guide on how to do this:

1. Find the Commit Hash

First, make sure you have the commit hash you are interested in. You can find it using git log or another command that displays commits.

 
git log --oneline

Note the commit hash of the commit you want to check.

2. List Branches Containing a Commit

Using git branch

You can use the --contains option with git branch to list branches that contain the specific commit:

 
git branch --contains <commit-hash>
  • <commit-hash>: Replace this with the hash of the commit you’re interested in.

Example:

 
git branch --contains a1b2c3d4

This command will list all local branches that contain the commit a1b2c3d4.

For Remote Branches

To check remote branches, use:

 
git branch -r --contains <commit-hash>
  • r: Specifies remote branches.

Example:

 
git branch -r --contains a1b2c3d4

This will list remote branches that contain the commit.

To List Both Local and Remote Branches

To list both local and remote branches, you can combine the two commands using:

 
git branch -a --contains <commit-hash>
  • a: Lists both local and remote branches.

Example:

 
git branch -a --contains a1b2c3d4

3. Use git reflog for Recent Commits

If you are interested in recent commits and want to check which branches contain them, you might also find git reflog useful. However, note that git reflog shows the history of branch updates and isn’t directly used to list branches containing specific commits but can be helpful for tracking recent activities.

Summary

  • List Local Branches Containing a Commit:

     
    git branch --contains <commit-hash>
    
  • List Remote Branches Containing a Commit:

     
    git branch -r --contains <commit-hash>
    
  • List Both Local and Remote Branches Containing a Commit:

     
    git branch -a --contains <commit-hash>
    

Using these commands, you can easily identify which branches have a specific commit in their history, helping with tasks like branch management and understanding code integration points.

Got an article suggestion? Let us know
Explore more
Git
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.