Git结账 - 切换回HEAD

asd*_*fgh 23 git git-checkout

我一直在做我的项目,但在某些时候我发现有一件事停止了工作.当我的代码工作正常时,我需要查看我的代码状态,所以我决定使用git checkout(因为我想检查一些东西).所以我做到了

git checkout SHA
Run Code Online (Sandbox Code Playgroud)

几次回到我不能去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
Run Code Online (Sandbox Code Playgroud)

我非常确定我没有改变任何东西.命令

git checkout master
Run Code Online (Sandbox Code Playgroud)

给出相同的输出.

有办法回到HEAD吗?

"跳过"历史记录提交的安全方式是什么?

Saj*_*han 21

您可以stash(保存临时框中的更改)然后返回master分支HEAD.

$ git add .
$ git stash
$ git checkout master
Run Code Online (Sandbox Code Playgroud)

跳过提交后退:

  • 转到具体的commit-sha.

    $ git checkout <commit-sha>
    
    Run Code Online (Sandbox Code Playgroud)
  • 如果此处有未提交的更改,则可以签出新分支,添加,提交,将当前分支推送到远程.

    # checkout a new branch, add, commit, push
    $ git checkout -b <branch-name>
    $ git add .
    $ git commit -m 'Changes in the commit'
    $ git push origin HEAD        # push the current branch to remote 
    
    $ git checkout master         # back to master branch now
    
    Run Code Online (Sandbox Code Playgroud)
  • 如果您在特定提交中有更改并且不想保留更改,则可以执行stashreset然后签出master(或任何其他分支).

    # stash
    $ git add -A
    $ git stash
    $ git checkout master
    
    # reset
    $ git reset --hard HEAD
    $ git checkout master
    
    Run Code Online (Sandbox Code Playgroud)
  • 如果您没有未提交的更改,那么在签出特定提交之后,只需返回masterother分支.

    $ git status          # see the changes
    $ git checkout master
    
    # or, shortcut
    $ git checkout -      # back to the previous state
    
    Run Code Online (Sandbox Code Playgroud)

  • @rbraun,我已经编辑了我的答案,显示你如何来回跳过提交. (2认同)
  • 在 git 2.17.1 中, `git checkout master` =&gt; "_error: pathspec 'master' 与 git_ 已知的任何文件都不匹配",但是 `git checkout -` 没问题。 (2认同)
  • ```git checkout main``` 对我有用 (2认同)

Scr*_*die 7

简答

git reset --hard
git checkout HEAD
Run Code Online (Sandbox Code Playgroud)

这将删除所有更改并让您返回到原来的分支 HEAD。