fancy
fancy

Reputation: 51383

How can I go back to the last commit without losing work?

I just made a commit and accidentally left in some files I should have removed. How can I undo this commit without losing any of the work? I want to undo that commit, go in and remove 2 files and then recommit all the changes.

Thanks!

Upvotes: 1

Views: 655

Answers (2)

tomieq
tomieq

Reputation: 29

First stash your current work

git stash

then start interactive rebase:

git rebase -i HEAD~5

you will see a list of your commits, e.g:

pick ff9c256 Added file manager logic
pick 8e09710 Added file manager UI

change 'pick' into 'e' to go into edit mode of your commit eg:

e 8e09710 Added file manager UI

then add/remove files from commit, edit files you want to change in your commit,

then

git commit --amend

and in the end

git rebase --continue

to go to the last commit and

git stash apply

to restore your current work progress

Upvotes: 1

Matt Ball
Matt Ball

Reputation: 359816

You don't need to undo anything. As long as you haven't pushed the commit:

git commit -a --amend -C HEAD

will amend the commit you just made, keeping the same commit message, committing any updated or deleted (but not untracked new) files.


so if i remove the files and then run that it will add it to the commit?

Yes, and if you want to be super-safe you can git rm the files and drop the -a flag:

git rm files/to/delete
git commit --amend -C HEAD

Upvotes: 1

Related Questions