Fix a Git detached head?

前端 未结 23 1327
臣服心动
臣服心动 2020-11-22 05:42

I was doing some work in my repository and noticed a file had local changes. I didn\'t want them anymore so I deleted the file, thinking I can just checkout a fresh copy. I

相关标签:
23条回答
  • 2020-11-22 06:21

    Detached head means:

    1. You are no longer on a branch,
    2. You have checked out a single commit in the history

    If you have no changes: you can switch to master by applying the following command

      git checkout master
    

    If you have changes that you want to keep:

    In case of a detached HEAD, commits work like normal, except no named branch gets updated. To get master branch updated with your committed changes, make a temporary branch where you are (this way the temporary branch will have all the committed changes you have made in the detached HEAD), then switch to the master branch and merge the temporary branch with the master.

    git branch  temp
    git checkout master
    git merge temp
    
    0 讨论(0)
  • 2020-11-22 06:21

    This works for me, It will assign a new branch for detached head :

    git checkout new_branch_name detached_head_garbage_name

    0 讨论(0)
  • 2020-11-22 06:21
    git pull origin master
    

    worked for me. It was just about giving remote and branch name explicitly.

    0 讨论(0)
  • 2020-11-22 06:23

    Normally HEAD points to a branch. When it is not pointing to a branch instead when it points to a commit hash like 69e51 it means you have a detached HEAD. You need to point it two a branch to fix the issue. You can do two things to fix it.

    1. git checkout other_branch // Not possible when you need the code in that commit hash
    2. create a new branch and point the commit hash to the newly created branch.

    HEAD must point to a branch, not a commit hash is the golden rule.

    0 讨论(0)
  • 2020-11-22 06:24

    you probably did git reset --hard origin/your-branch.

    Try to just git checkout your-branch

    0 讨论(0)
  • 2020-11-22 06:25

    If you made changes and then realized that you are on a detached head, you can do: stash -> checkout master -> stash pop:

    git stash
    git checkout master   # Fix the detached head state
    git stash pop         # Or for extra safety use 'stash apply' then later 
                          #   after fixing everything do 'stash drop'
    

    You will have your uncommited changes and normal "attached" HEAD, like nothing happened.

    0 讨论(0)
提交回复
热议问题