2

I often do this:

git add -u
git commit

...discover mistake, fix it...

git add -u
git commit -m "Fix typo"

Is there an easy way to squash the second commit back into the first? Sometimes I can do it with git rebase -i, but sometimes I just get a message about being up to date.

Note I'm only really talking about situations where I haven't pushed the first commit. Basically I want to use the first log message, but with the combined effect of the two commits. Can I use git commit --amend for such things?

This related question kind of dealt with this: git: squash/fixup earlier commit

The best answer is a year old though, and I wonder if things have improved?

Community
  • 1
  • 1
Steve Bennett
  • 114,604
  • 39
  • 168
  • 219

3 Answers3

6

This is exactly what git commit --amend is for. Given your example, all you need to do is add the --amend flag to your second commit:

git add -u
git commit

...discover mistake, fix it...

git add -u
git commit --amend

You can do this visually in git gui also (there is a radio-box to toggle between "new commit" and "amend last commit")

dbr
  • 165,801
  • 69
  • 278
  • 343
  • Interesting - didn't know about `git gui`. I wonder why there's both that and gitk. (Competing for the ugly prize? :p ) – Steve Bennett Mar 27 '12 at 10:51
  • These two have different purposes: `git gui` is for commiting, and `gitk` is for viewing and managing branches. Note that you can start `git gui` from `gitk` and vice versa. – François Mar 27 '12 at 11:42
1

The best I've found is this article that talks about the autosquash feature introduced in git 1.7.

http://technosorcery.net/blog/2010/02/07/fun-with-the-upcoming-1-7-release-of-git-rebase---interactive---autosquash/

Waynn Lue
  • 11,344
  • 8
  • 51
  • 76
0

Yes, you can just amend the previous commit.

git add typointhisfile
git commit -vm

OR if you've already created 2 commits - you can make them one with:

git rebase -i HEAD~2

Just squash one of them into the other.

You're better off (IMO) though, preventing the problem in the first place. And for that I suggest always doing verbose commits:

git commit -v

Before writing the commit message - skim the diff of the changes you are going to commit, and just close your editor if you see something you need to correct. Closing without entering a commit message will abort the commit.

Make it a habit and the need to commit typo-corrections will all but disappear.

AD7six
  • 63,116
  • 12
  • 91
  • 123
  • Yeah. I actually do lots of visual checks (git diff --cached, in particular). Still easy to miss stuff. And of course, you're *supposed* to commit often. So it doesn't make sense to hold off committing until everything is perfect... – Steve Bennett Mar 27 '12 at 10:48
  • committing often and committing mistakes are 2 different things @SteveBennett – AD7six Mar 27 '12 at 10:49