2

I do a lot of squashing where I only care about the commit message of the first commit. currently I use the well-known git rebase -i head~n, which makes this time-wasting multi-step processes. I've been reading other responses and none of them do exaclty what i need.

basically im trying to achieve with one command what the following git interactive rebase editor will achieve after saving (ex.: for the last 4 commits):

pick 80a1ee7 COMMIT MESSAGE I want to preserve
f 0b95426 commit message that doesnt matter
f 79e92f1 commit message that doesnt matter
f bc10c06 commit message that doesnt matter

ANSWER: none of the answers in the other posts do exactly what I want, so even though this was marked as duplicate, here is a solution that combines some of the answers in the linked posts.

the major difference being that I want to preserve only the nth commit's message.

1. Create script for squashing (squash.sh)

#!/bin/sh
#

# get number of commits to squash
n=$1

# validate that n is an integer
regex="^[0-9]+$"
if ! [[ $n =~ $regex ]]; then
    echo "error: Squash count must be an integer."
    exit 0
fi

# get the nth commit message
skip=$(( $n - 1 ))
nthMessage=$(git log --skip=$skip --max-count=1 --pretty=%B)

# do the squash
git reset --soft HEAD~$n
git commit -m "$nthMessage"

exit 0

2. add alias in .gitconfig

squash = !sh -c '<path-to>/squash.sh $1' -

3. do the squashing with (ex.: for the last 4 commits):

git squash 4
2
  • For preserving all commit messages, see, e.g., stackoverflow.com/a/21890252/1256452, and note also that you can use -C <commit-specifier> to pick one particular commit's message (you can add either --edit or --no-edit to explicitly edit or not edit the message).
    – torek
    Commented May 12, 2017 at 20:01
  • Creating an alias that do git reset --soft head~n-1 and git commit --amend should work (so the n-1 yourself and pass it to the alias).
    – Philippe
    Commented May 12, 2017 at 21:37

0

Browse other questions tagged or ask your own question.