brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: git merge-base --is-ancestor tells a script if one commit is already in another

Git
~/tips/tip-git-merge-base-is-ancestor

git merge-base --is-ancestor main feat

Answers yes or no through the exit code whether a commit is part of another commit's history.

Is this branch already merged? Is the fix in the release? Reading git log output works for a human, but a script wants a clean yes or no.

git merge-base --is-ancestor main feat
echo $?

It prints nothing. The answer is the exit code: 0 when the first commit is an ancestor of the second (or the same commit), 1 when it isn’t. Errors, like a typo in a branch name, give a different code, so check for 1 specifically if you need to tell them apart.

In a throwaway repository where feat branched off main and has one more commit, asking whether main is an ancestor of feat returns 0. Swapping the two gives 1. That reads as: is everything in main already inside feat? In a script, put the call in an if and the exit code does the rest.

if git merge-base --is-ancestor v1.4 HEAD; then
  echo "fix is included"
fi

Caveat: it only knows about commits. A fix that was cherry-picked has a new hash, so the original commit is not an ancestor and you get 1 even though the change is there. For that case git cherry or git log --cherry-pick is closer to what you want.

Further reading: git-merge-base documentation

More Git tips git show-branch main feature git log --stat -5 git merge --no-ff feature -m "Merge feature" git merge --squash feature git merge --abort All Git tips (144) All topics

Link