Git 签出-切换回 HEAD

我一直在做我的项目,而在某个时候,我发现一件事情停止工作。我需要在代码正常工作时查找它的状态,所以我决定使用 git checkout (因为我想签出某些东西)。我也这么做了

git checkout SHA

返回几次我无法进入 HEAD 的点,输出如下:

git checkout SHA-HEAD


error: Your local changes to the following files would be overwritten by checkout:
[list of files]
Please, commit your changes or stash them before you can switch branches.
Aborting

我非常肯定我没有改变任何东西

git checkout master

输出相同。

有没有办法回到 HEAD?

“跳过”历史承诺的安全方式是什么?

206577 次浏览

You can stash (save the changes in temporary place) then, back to master branch HEAD.

$ git add .
$ git stash
$ git checkout master

Note that some sites have changed the name of the default branch from "master" to "main" so you might have to use git checkout main instead.


Jump Over Commits Back and Forth:

  • Go to a specific commit-sha.

      $ git checkout <commit-sha>
    
  • If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.

      # checkout a new branch, add, commit, push
    $ git checkout -b <branch-name>
    $ git add .
    $ git commit -m 'Commit message'
    $ git push origin HEAD          # push the current branch to remote
    
    
    $ git checkout master           # back to master branch now
    
  • If you have changes in the specific commit and don't want to keep the changes, you can do stash or reset then checkout to master (or, any other branch).

      # stash
    $ git add -A
    $ git stash
    $ git checkout master
    
    
    # reset
    $ git reset --hard HEAD
    $ git checkout master
    
  • After checking out a specific commit if you have no uncommitted change(s) then, just back to master or other branch.

      $ git status          # see the changes
    $ git checkout master
    
    
    # or, shortcut
    $ git checkout -      # back to the previous state
    

Short Answer

git reset --hard
git checkout HEAD

This removes any (undesired) changes and gets you back to the branch HEAD where you came from.