Instantly share code, notes, and snippets.

Embed
What would you like to do?
Script to squash the last Git commit
#!/bin/bash -e
HEAD_COMMIT_MESSAGE=$(git log --format=%B -1 HEAD)
# For safety. Our use-case is usually to always just squash into a commit
# that's associated with an active change. We really don't want lose our head
# and accidentally squash something that wasn't intended to be squashed.
if [[ "${HEAD_COMMIT_MESSAGE}" != SQUASH* ]]; then
echo "SQUASH: Commit to be squashed should have 'SQUASH' as its commit-message."
exit 1
fi
_FILEPATH=$(mktemp)
git log --format=%B -1 HEAD~1 >"${_FILEPATH}"
echo "Initial head: $(git rev-parse HEAD)"
git reset --soft HEAD~2 >/dev/null
echo "Head after reset: $(git rev-parse HEAD)"
git commit -F $_FILEPATH >/dev/null
rm $_FILEPATH
echo "Head after commit: $(git rev-parse HEAD)"
echo
# Remember to alias this script as SQUASH_LAST.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment