Git: check if a commit exists on a given branch

To check if a commit SHA exists on a given branch, you have a couple of options.
git merge-base --is-ancestor
For a low-level query about commit existence, use git merge-base with its --is-ancestor option. This command only returns the result through its exit status, so it’s most useful for scripting.
$ git merge-base --is-ancestor <commit> <branch>
This command will exit with a status of 0 (success) if the commit is found on the branch, 1 (failure) if it is not, or 128 if either the commit or the branch don’t exist.
For example, if the commit exists:
$ git merge-base --is-ancestor a4ca614 origin/main
$ echo $?
0
…and if it does not:
$ git merge-base --is-ancestor a4ca614 upstream/main
$ echo $?
1
git branch --contains
For a higher-level query that can check multiple branches, use git branch with its --contains option to list all branches that contain the commit.
$ git branch --contains <commit>
For example:
$ git branch --contains a4ca614
delicious-jams
* main
The result here that the only local branches with that commit are delicious-jams and main.
Add -a (--all) to include remote-tracking branches in the output:
$ git branch -a --contains a4ca614
delicious-jams
* main
remotes/origin/HEAD -> origin/main
remotes/origin/main
To query only certain branches, add their names. For example, to check only origin/main and upstream/main:
$ git branch -r --contains a4ca614 origin/main upstream/main
remotes/origin/main
This result tells us that the commit appears in origin/main but not in upstream/main.
You can also use shell wildcard patterns to match branch names. For example, to check all upstream branches:
$ git branch -r --contains a4ca614 'upstream/*'
No output here means that no matching branches contain the commit.
😸😸😸 Check out my new book on using GitHub effectively, Boost Your GitHub DX! 😸😸😸
One summary email a week, no spam, I pinky promise.
Related posts:
- Git: count files in a repository
- Git: find the largest commits
- Git: automatically stash while rebasing or merging with autostash
Tags: git