デタッチド HEAD と通常の HEAD でテストする
前のステップで、HEAD
は通常 master
のようなブランチを指すことを学びました。これが「通常」の状態です。しかし、HEAD
は特定のコミットを直接指すこともできます。これは「デタッチド HEAD」状態と呼ばれます。
デタッチド HEAD
がどのような状態か見てみましょう。まず、最初のコミットのコミット ID が必要です。これは git log --oneline
を使って取得できます。
cd ~/project/my-time-machine
git log --oneline
以下のような出力が表示されるはずです(コミット ID はあなたの環境で異なります)。
a1b2c3d (HEAD -> master) Send a message to the future
最初の 7 文字(この例では a1b2c3d
)が短縮コミット ID です。この ID をコピーしてください。
では、git checkout
を使って HEAD
をこのコミットを直接指すように移動させましょう。
git checkout <your_commit_id>
<your_commit_id>
を git log --oneline
からコピーした実際の短縮コミット ID に置き換えてください。例えば:
git checkout a1b2c3d
デタッチド HEAD 状態に入ったことを示す出力が表示されます。
Note: switching to 'a1b2c3d'.
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 by switching back to a branch.
If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -c with the switch command. Example:
git switch -c <new-branch-name>
Or, if you want to make this branch stay, use:
git branch <new-branch-name> <your_commit_id>
Switched to commit a1b2c3d
では、再度ステータスを確認しましょう。
git status
出力は、あなたがデタッチド HEAD 状態にあることを明確に示します。
HEAD is now at a1b2c3d Send a message to the future
nothing to commit, working tree clean
そして、git symbolic-ref HEAD
を使うと、HEAD
がブランチへのシンボリックリファレンスではないため、エラーが表示されます。
git symbolic-ref HEAD
このコマンドはおそらくエラーを表示するか、何も出力されず、HEAD
がシンボリックリファレンスではないことを示します。
HEAD
が master
ブランチを指す通常の状態に戻るには、master
ブランチにチェックアウトします。
git checkout master
以下のような出力が表示されるはずです。
Switched to branch 'master'
これで、git status
はあなたが master
ブランチに戻ったことを示します。
git status
出力:
On branch master
nothing to commit, working tree clean
そして、git symbolic-ref HEAD
は再びシンボリックリファレンスを表示します。
git symbolic-ref HEAD
出力:
refs/heads/master
アタッチド HEAD
(ブランチを指す)とデタッチド HEAD
(コミットを直接指す)の違いを理解することは、プロジェクトの履歴を操作し、高度な Git 操作を行うために重要です。