squash-last-commit.sh

squash-last-commit.sh

By devin, 16 December, 2015

Sometimes you make a git commit, but there's a typo or syntax error in there by accident. I normally use

git rebase -i HEAD~2

and then through the magic of vim I'm fairly productive at squashing the two commits together.

But wouldn't it be nice if there was a way to run one command to squash your most recent commit (which probably has a useless message like "typo" anyway) into the next most recent? Lucky for you, there is now!

#!/bin/bash
#
# Devin Howard 2015
# squash-last-commit.sh
#
# Squashes your most recent commit into the next most recent, erasing its message from the log
# Example usage:
# $ vim # make a small fix, like a typo or a syntax error
# $ git add .
# $ git commit -m "blah typo squash me"
# $ git log HEAD~2..HEAD
#
# commit 4c31808f959b4d2c36601ab2fa2ccbb3b7863477
# Author: Devin Howard <devin@callysto.com>
# Date:   Thu Dec 17 11:21:20 2015 +0800
#
#     blah typo squash me
#
# commit e90ac5d3b2c3c60bf6ba9f8bd6b69577f1a95243
# Author: Devin Howard <devin@callysto.com>
# Date:   Thu Dec 17 11:21:10 2015 +0800
#
#     really great new feature
#
# $ squash-last-commit.sh
# $ git log HEAD~2..HEAD
#
# commit e90ac5d3b2c3c60bf6ba9f8bd6b69577f1a95243
# Author: Devin Howard <devin@callysto.com>
# Date:   Thu Dec 17 11:21:10 2015 +0800
#
#     really great new feature
#
# commit e90ac5d3b2c3c60bf6ba9f8bd6b69577f1a95243
# Author: John Johnsterson <john@johnsterson.com>
# Date:   Thu Dec 10 09:17:00 2015 +0800
#
#     update code for latest cool feature
#

if [[ "$1" == "--commit" || "$1" == "-c" ]]; then
  git add -A .
  git commit -m "squashit"
fi

export GIT_EDITOR=ed

cat << EOF | git rebase -i HEAD~2
2s/^pick/fixup/
wq
EOF

Plain text

  • No HTML tags allowed.
  • Web page addresses and email addresses turn into links automatically.
  • Lines and paragraphs break automatically.