0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

個人的備忘録:Gitエラー「fatal: could not parse HEAD」の原因と解決方法を整理してみた

Posted at

はじめに

Gitを使ってプロジェクトの管理をしていると、ごくまれにリポジトリの内部状態が壊れてしまい、通常のコマンドが正常に動作しないことがあります。

個人の備忘録程度の走り書きとなっておりますが、温かい目で見守っていただければ幸いです。

本記事では、「fatal: could not parse HEAD」などのエラーが出た際の原因と対処法について解説します。

書こうと思ったきっかけ

Gitのリポジトリを再初期化した際に、想定外のエラーに遭遇し、調査と対処に時間を要しました。同じようなエラーに直面した方の参考になればと思い、備忘録として記録しています。

Gitエラー「fatal: could not parse HEAD」の原因と解決策

発生したコマンドとエラー

© ~/Desktop/hondasr.com  (git)-[main]-  git init
Reinitialized existing Git repository in /Users/xxx/Desktop/hondasr.com/.git/
© ~/Desktop/hondasr.com  (git)-[main]-  git add .
© ~/Desktop/hondasr.com  (git)-[main]-  git commit -m "first commit"
fatal: could not parse HEAD
© ~/Desktop/hondasr.com  (git)-[main]-  git commit -m "first commit"
fatal: could not parse HEAD
© ~/Desktop/hondasr.com  (git)-[main]-  git branch -M main
error: unable to write current sha1 into refs/heads/main: trying to write ref 'refs/heads/main' with nonexistent object f05718b626341e51933981f637a4f7bd57a5d781
fatal: branch rename failed

現象の概要

エラー内容 原因
fatal: could not parse HEAD .git/HEADが壊れている、または初期化が不完全
unable to write current sha1 into refs/heads/main mainブランチの参照元Gitオブジェクトが存在しない
branch rename failed .git/refs/heads/mainが作れない状態

解決策

方法: Git初期化をやり直す(おすすめ)

壊れた .git フォルダを削除して、再度初期化します:

rm -rf .git
git init
git add .
git commit -m "first commit"

この手順でほぼ確実に正常な状態に戻ります。

補足

以下のような状況で、このようなGit内部の壊れは発生しがちです:

  • .gitフォルダを手動でいじった
  • 古いバックアップからプロジェクトを復元した
  • Git操作中にディスクエラーや電源切れが発生

バックアップを取っておきたい場合

Git内部を削除する前に一時的に保管しておく場合:

mv .git ../git-backup

何か証拠を残しておきたい場合に有用です。

まとめ

「fatal: could not parse HEAD」エラーは、Gitリポジトリ内部の不整合や壊れた参照が原因で発生します。

最も安全かつ確実な対処法は、.git フォルダを削除して再初期化する方法です。

同様のエラーに出会った際には、冷静に原因を切り分けてみてください!

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?