Skip to content

Instantly share code, notes, and snippets.

@k0pernikus
Created October 9, 2025 12:32
Show Gist options
  • Select an option

  • Save k0pernikus/650b06750d6e4b9142c1d927bc82ddbe to your computer and use it in GitHub Desktop.

Select an option

Save k0pernikus/650b06750d6e4b9142c1d927bc82ddbe to your computer and use it in GitHub Desktop.
git purge merge commit from history
#!/usr/bin/env bash
N=${1:-5}
if ! git rev-parse --is-inside-work-tree > /dev/null 2>&1; then
echo "Error: Not inside a Git repository."
exit 1
fi
git log --merges -n "$N" \
--pretty=format:$'%C(yellow)%H%C(reset)\t%C(cyan)%ad%C(reset)\t%s' \
--date=short --color=always \
| sed "s/\tMerge branch '\([^']*\)' into .*$/\t\1/"
echo
exit 0
#!/usr/bin/env bash
MERGE_SHA=$1
if [ -z "${MERGE_SHA}" ]; then
echo "Error: Please provide the merge commit SHA."
exit 1
fi
if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
echo "Error: Not inside a Git repository."
exit 1
fi
if ! git diff-index --quiet HEAD --; then
echo "Error: Working directory is not clean."
echo "Please commit, stash, or reset your changes before running this command."
exit 1
fi
BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)
FIRST_PARENT=$(git rev-parse "${MERGE_SHA}^1")
cat <<EOF
Starting to purge merge from history (local only, no force pushing)
Target Branch: ${BRANCH_NAME}
Merge to Undo: ${MERGE_SHA}
New Base (First Parent): ${FIRST_PARENT}
EOF
if git rebase --onto "${FIRST_PARENT}" "${MERGE_SHA}" HEAD; then
git branch -f "${BRANCH_NAME}" HEAD
git checkout "${BRANCH_NAME}"
cat <<EOF_SUCCESS
Merge Undo Successful
History rewritten. The merge commit is gone.
Local branch is now at the new tip.
WARNING: To update the remote branch, run:
git push --force-with-lease origin ${BRANCH_NAME}
EOF_SUCCESS
exit 0
else
cat <<'EOF_FAILURE'
Rebase Failed ---
The rebase stopped due to conflicts or an error. Resolve conflicts, then run:
git rebase --continue
If you want to abort, run:
git rebase --abort
EOF_FAILURE
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment