Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I undo my last git add/commit?

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

like image 297
dave Avatar asked Dec 21 '10 10:12

dave


People also ask

Can we revert the last commit in git?

The revert command You can find the name of the commit you want to revert using git log . The first commit that's described there is the last commit created. Then you can copy from there the alphanumerical name and use that in the revert command.

How can I delete my last commit?

To remove the last commit from git, you can simply run git reset --hard HEAD^ If you are removing multiple commits from the top, you can run git reset --hard HEAD~2 to remove the last two commits. You can increase the number to remove even more commits.


1 Answers

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.

like image 182
Gauthier Avatar answered Sep 22 '22 17:09

Gauthier