简体   繁体   中英

“git reset --hard HEAD” in master branch deleted unstaged changes in local branch

I have some local changes in master branch which I merged into local branch.

local>git merge master

After this I wanted a clean master repository so I went to master and did git reset head.

local>git checkout master
master> git reset --hard HEAD

Then I went back to local branch and noticed that all my unstaged changes in local has been lost. Why is it so?

When you switched from local to master via git checkout master , your changes in the working directory remained intact as they were. Except now you were on the master branch. When you did:

git reset --hard HEAD

from the master branch, you reset both your working directory and stage to the HEAD commit from the master branch. Hence, I expect that your working directory changes are lost.

There is one possibility to recover your working directory though. If you are using a good IDE like IntelliJ, then it may remember the state of the files you modified before Git reset them. To test this, just look at a file in question and try doing an undo. If you are lucky, you may get your old changes back this way.

For future reference, if you had working changes on local and you wanted to switch branches in this way, you could have tried doing one of the following

  • Use git stash to make a stash with your work
  • Make a temporary commit on local .

If you stash, you can later apply those changes again via git stash apply . In the case of a temporary commit, when you return to local later on you can complete your work and then amend that temporary commit via:

git commit --amend

Note that under the hood git stash itself makes 2 (sometimes three) commits to persist the working directory and stage on a given branch.

There are three stages in Git,

  1. Unstaged changes (dirty, working code)
  2. Staged changes (clean, commitable code)
  3. Committed, Pushed changes (fully-tested, deployable code)

When you reset, all dirty working code (in Stage 1) will be deleted for no branch takes ownership for that.

If you want to "save" local dirty working copies, try git stash .

A more visual aided way to show the stage of your changes is via git gui .

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