Given a commit id, how to determine if current branch contains the commit?

There are multiple ways to achieve this result. First naive option is to use git log and search for a specific commit using grep, but that is not always precise

git log | grep <commit_id>

You are better off to use git branch directly to find all branches containing given COMMIT_ID using

git branch --contains $COMMIT_ID

The next step is finding out current branch which can be done since git 1.8.1 using

git symbolic-ref --short HEAD

And combined together as

git branch $(git symbolic-ref --short HEAD) --contains $COMMIT_ID

But the command above doesn’t return true or false and there is a shorter version that returns exit code 0 if commit is in current branch OR exit code 1 if not

git merge-base --is-ancestor $COMMIT_ID HEAD

Exit code is nice, but as you want string true or false as answer you need to add a bit more and then combined with if from bash you get

if [ 0 -eq $(git merge-base --is-ancestor $COMMIT_ID HEAD) ]; then echo "true"; else echo "false"; fi

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)