27

I edited a file and did:

git add file.py
git commit -m 'fixed bug'

I then edited another file and performed a minor bug fix. I don't want two commits, one after the other, showing 'bug fix'. I want one commit with 'bug fixes'.

How can I undo the last add/commit and change the first commit message?

I was looking at the git reset, git revert, git undo commands but I don't want to screw up my repo with a guess

EDIT: Found out how to do it: http://www.gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html

dave
  • 7,717
  • 19
  • 68
  • 100

1 Answers1

48

If you already commited your second change, reset it first:

git reset HEAD^

Now your HEAD is at the first commit, and the content of your local files is unchanged.

git add <the file(s) for the second bug fix>
git commit --amend -m'bug fixes'

If all tracked and changed file are to be included for the second bug fix, you can run this instead, as usual:

git commit -a --amend

Amending the commit is exactly this:

  • adds the changes in index to the previous commit (therefore the need for git add, or -a)
  • allows you to change your commit message

Be careful, though: if you have distributed the first commit, other people's repo will get strange. You should not change a commit that someone else has fetched.


You could also probably use git merge --squash, which feels more logical but not necessarily easier. Use it to merge a branch containing your two commits, unto the previous commit.

Squashing works with git rebase as well.

Gauthier
  • 40,309
  • 11
  • 63
  • 97
  • With the two I files I edited, I already did `git add file; git commit`. Doing `git --amend -m 'asd'` would just edit my previous commit message, wouldn't it? Leaving the first commit in the log? – dave Dec 21 '10 at 10:32
  • No, `--amend` adds the content of the index to the newly created commit. The old commit disappears (becomes dangling). Chances are that you can still see it in gitk, run a reload (Ctrl+F5) in gitk to make it disappear. The dangling commit will disappear from memory later on (`git gc` should clean it out). – Gauthier Dec 21 '10 at 10:33
  • did you commit twice already? In that case you can precede the commands above with `git reset HEAD^`. Please backup your repo before doing all this (make sure the folder .git is in your backup), I don't want to be responsible of data loss. – Gauthier Dec 21 '10 at 10:38
  • I don't have anything in the index. I have two commits that I want to merge into one... – dave Dec 21 '10 at 10:39