Skip to content

Instantly share code, notes, and snippets.

@michpohl
Last active December 20, 2021 15:25
Show Gist options
  • Save michpohl/62aa08566ff82e90c5f2d76426dc3fa0 to your computer and use it in GitHub Desktop.
Save michpohl/62aa08566ff82e90c5f2d76426dc3fa0 to your computer and use it in GitHub Desktop.
Quickly squash n git commits into the n+1th
#!/bin/bash
# Script to quickly squash the last n commits in your current git branch into the n+1th.
# The n+1th commit message is re-used, the others are discarded
# user input
COUNT="$1"
if [[ -z $COUNT ]] ; then
printf "Usage: fixtop.sh [NUMBER]\nThis will squash the specified number of commits into the one right before.\n"
printf "Example: \"fixtop.sh 3\" will squash the newest 3 commits into the fourth."
exit 1
fi
# Find information from git
TARGET_SHA=$(git rev-parse HEAD~$(($COUNT)))
TARGET_MESSAGE=$(git show --pretty=format:%s -s $TARGET_SHA)
FIXED_MESSAGE=$(sed '1 s/"//gp' <<< "$TARGET_MESSAGE")
# Ask for user confirmation
COMMITS_TO_SQUASH=$(git log -$COUNT --oneline)
COMMIT_TO_SQUASH_INTO=$(git show --oneline -s $TARGET_SHA)
printf "\nDo you want to squash these commits:\n%s" "$COMMITS_TO_SQUASH"
printf "\ninto:\n%s" "$COMMIT_TO_SQUASH_INTO"
read -r -p "(y/n)"
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
echo "Aborted!"
exit 1
fi
# squash
git reset --soft HEAD~$COUNT && git commit -m "FIXED_MESSAGE"
echo "Done."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment