简体   繁体   中英

git - How to undo changes to a locally committed file

I did following, all while on my local BranchA :

  1. Modify FileA (by mistake)
  2. git add FileA
  3. git commit -m "Modified FileA"

So, FileA is in my local commit (never pushed to remote) on my local branch BranchA (also never pushed to remote).

How do I revert changes to FileA?

UPDATE AND HOW I SOLVED IT

I undoed changes to FileA from SourceTree instead from git as I realized it is simpler for me.

To do so, in SourceTree, rc on commited file FileA > "Log Select ..." > select the previous commit (the one before yours) > rc on it and choose "Reset to this commit". That did the job but thank you all

To specifically undo the changes in that file but keep the commit unchanged otherwise :

1) Revert fileA to its previous state

git checkout HEAD^ -- path/to/fileA

2) Include that in the last commit you did on BranchA

git commit --amend

(And since it has not been pushed yet, no need to push with force next time.)

First you reset your branch to the previous commit:

git reset @^ --mixed

Then you can use checkout to reset specific files to the old state:

git checkout -- files...

Once you have done that you can re-commit your changes:

git add files...
git commit -m "message"

You can reset the current branch index to the previous commit with git reset HEAD~1 . Add --hard to reset your working directory, or leave it off if you want to refine the changes and recommit.

If you have other changes that you made since then, use git rebase to move your offending commit to the top of the stack first.

Another way to do it (I assume your commit has changes only in files, you want to discard):

Being in your BranchA

git rebase -i HEAD~2

It will give a list of two commits, sorted historically asc. The last one is what you would like to change. So, you want to discard that commit. Move cursor to the second commit, and instead of pick type drop , or just d .

Save your changes (depends on your editor, it could be CTRL + X + SHIFT + Y for nano or :wq for vim , and that is it.

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