简体   繁体   中英

How can I undo latest commit and retain changes?

I have several commits already and I need to undo the latest one but to have changes I made in it in place. Please advice how to do that. Thank you.

git reset --soft HEAD^

Note that you should only rewind HEAD if it's not pushed yet.


edit In response to your comment on the original question:

If you only want to edit the most recent commit, Git has a neat feature commit --amend . Simply use git add / git rm / git checkout until your index is in the state you want it to be (new changes added, some changes thrown away, files removed, …). Then use git commit --amend , it will pop up vi (or whatever you have configured in core.editor ) with your last commit's commit message for you to edit.

Note, that when I say ›edit the most recent commit‹, Git actually creates a new commit. So don't do it, when the commit was already pulled from other people (ie pushed to your public repository)

If you want to update the most recent commit , then amending this commit would do the job:

<do the changes you want to>
git add <missing files>
git add <changed files>
git commit --amend

That's it.

If you need to change comment and add some other files to previous commit , I suggest you do interactive rebase instead.

<do the changes you want to>
git add <missing files>
git commit -a
git rebase -i HEAD~3

In editor that pops up you'll see something like

pick <SHA1> Commit that you wanted to change
pick <SHA2> Next commit that you seem to try to rollback in your question
pick <SHA3> Just committed fixes to SHA1

Change it to be

pick <SHA1> Commit that you wanted to change
f <SHA3> Just committed fixes to SHA1
pick <SHA2> Next commit that you seem to try to rollback in your question

('f' means 'fixup' -- squash SHA1 ans SHA3 and discard commit message of SHA3 one)

Save changes, quit editor. You are done.

That should never be done for commits you've already pushed upstream.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM