Skip to content

Instantly share code, notes, and snippets.

@petrabarus
Created October 24, 2024 02:52
Show Gist options
  • Save petrabarus/33ae6fcc03088c6ca36e601276c5a7a5 to your computer and use it in GitHub Desktop.
Save petrabarus/33ae6fcc03088c6ca36e601276c5a7a5 to your computer and use it in GitHub Desktop.
Git Squash
#!/usr/bin/env bash
# This will receive arguments of number of commits to squash
# and use the earliest commit message as the new commit message
# Function to show usage
show_usage() {
echo "Usage: ./git-squash.sh <number_of_commits>"
echo "Example: ./git-squash.sh 3"
exit 1
}
# Get the number of commits to squash
# Check if number of commits is provided
if [ $# -ne 1 ] || ! [[ $1 =~ ^[0-9]+$ ]]; then
show_usage
fi
NUM_COMMITS=$1
# Get the earliest commit message from the last $NUM_COMMITS commits
EARLIEST_COMMIT_MESSAGE=$(git log --format=%B -n 1 HEAD~$(($NUM_COMMITS-1)))
# Create a temp file for the rebase command
TEMP_FILE=$(mktemp)
# Use reset instead of rebase
git reset --soft HEAD~$NUM_COMMITS
git commit -m "$EARLIEST_COMMIT_MESSAGE"
echo "Successfully squashed last $NUM_COMMITS commits using the message: $EARLIEST_COMMIT_MESSAGE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment