gitのHEADがブランチから外れてしまう現象とその直し方


detached HEADGit


t$ git init
Initialized empty Git repository in /Users/nishio/gittest/pygit2/t/.git/

t$ touch a
t$ git add a
t$ git commit -m "add a"
[master (root-commit) 6f6eb7c] add a
 0 files changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 a

t$ touch b
t$ git add b
t$ git commit -m "add b"
[master 62e58df] add b
 0 files changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 b

HEADHEADmastermaster
t$ cat .git/HEAD 
ref: refs/heads/master
t$ cat .git/refs/heads/master
62e58dfd8d36db9f649a163b097f35cef99b91a3

checkout
t$ git checkout 62e5
Note: checking out '62e5'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b new_branch_name

HEAD is now at 62e58df... add b

git


'detached HEAD'OK
-b():
 git checkout -b new_branch_name
HEAD  62e58df... add b
 

master

HEAD
t$ cat .git/HEAD 
62e58dfd8d36db9f649a163b097f35cef99b91a3


t$ touch c
t$ git add c
t$ git commit -m "add c"
[detached HEAD b17d3fd] add c
 0 files changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 c

master
t$ git log --oneline master
62e58df add b
6f6eb7c add a

mastermastergit
t$ git branch tmp1

mastermerge
t$ git checkout master
Previous HEAD position was b17d3fd... add c
Switched to branch 'master'
t$ git merge tmp1
Updating 62e58df..b17d3fd
Fast-forward
 0 files changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 c

tmp1c


t$ git branch -d tmp1
Deleted branch tmp1 (was b17d3fd).