I randomly hit this today while trying to run Git garbage collect:
$ git gc
fatal: bad object refs/remotes/origin/HEAD
error: failed to run repack
How do I deal with this?
Paulo Mattos
18.3k10 gold badges74 silver badges83 bronze badges
asked May 10, 2016 at 17:25
I don’t understand the ramifications of this, but as suggested in this thread, when I encountered this I just did
$ mv .git/refs/remotes/origin/HEAD /tmp
(keeping it around just in case) and then
$ git gc
worked without complaining; I haven’t run into any problems.
answered Jul 4, 2016 at 22:09
petrelharppetrelharp
4,7031 gold badge15 silver badges16 bronze badges
12
After seeing Trenton’s answer, I looked at my .git/refs/remotes/origin/HEAD
and saw that it was also pointing to an old branch that is now deleted.
But instead of editing the file myself, I tried Ryan’s solution:
git remote set-head origin --auto
It automatically set the file to the new branch, and git gc
worked fine after that.
answered Apr 20, 2018 at 14:44
WilQuWilQu
6,9836 gold badges30 silver badges38 bronze badges
3
The problem that I ran into (which is the same problem that @Stavarengo mentioned in this comment above) is that the default remote branch (develop
in my case) had been deleted, but was still referenced in .git/refs/remotes/origin/HEAD
.
Opening .git/refs/remotes/origin/HEAD
in my editor showed this:
ref: refs/remotes/origin/develop
I carefully edited it to point at my new default branch and all was well:
ref: refs/remotes/origin/master
The clue that tipped me off was that running git prune
showed this error:
> git prune
warning: symbolic ref is dangling: refs/remotes/origin/HEAD
answered Sep 11, 2017 at 16:08
TrentonTrenton
1,3981 gold badge9 silver badges7 bronze badges
4
Thank god I found this
https://makandracards.com/chris-4/54101-fixing-a-git-repo
fatal: bad object refs/remotes/origin/HEAD
error: failed to run repack
This may happen if upstream branches have been removed and your origin is pointing to it. You can confirm this by running:
cat .git/refs/remotes/origin/HEAD
If it is pointing to a branch that doesn’t exist, running:
git remote set-head origin --auto
followed by
git gc
will fix it
answered Apr 19, 2021 at 13:15
2
Looks like your symbolic-refs might be broken…
Try the replacing it with your default branch like this:
For example, my default branch is master
$ git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/master
$ git fetch --prune
$ git gc
That should fix it.
answered Mar 16, 2020 at 21:57
1
git update-ref -d [wrong reference here]
This will fix this issue.
For above issue use following code:
git update-ref -d 'refs/remotes/origin/HEAD'
In case you are getting error with .git like below:
error: bad ref for .git/logs/refs/remotes/origin/Dec/session-dynatrace-logs 6
You can copy the path starting from refs like below:
git update-ref -d 'refs/remotes/origin/Dec/session-dynatrace-logs 6'
answered Oct 27, 2020 at 18:56
3
I hit this error because the default branch was changed from master
to main
.
I used a mix of info given by a few of the answers above to resolve it:
cat .git/refs/remotes/origin/HEAD
Returned:
ref: refs/remotes/origin/master
To fix it, I ran:
git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/main
I ran this again to double-check:
cat .git/refs/remotes/origin/HEAD
Which returned:
ref: refs/remotes/origin/main
Then git gc
and git prune
worked just fine.
To see what happens I also tried:
git remote set-head origin --auto
Which returned:
origin/HEAD set to main
And it really solves the problem by identifying the ref automatically.
answered Nov 10, 2021 at 12:26
Virtua CreativeVirtua Creative
1,9751 gold badge13 silver badges17 bronze badges
The above solution partially worked for me because my folder had the «desktop.ini» files everywhere in the repository as it is hosted on Google Drive, including the “.git” folders where Git was storing its own data. Git expected every file in that folder to contain Git data, not Google Drive data, and it choked trying to interpret the desktop.ini file contents.
To avoid this, make sure to include desktop.ini
in .gitignore
I first deleted these files using a batch command on windows as follows:
-
create a «delete.bat» file in the repository and add the following code to it
del /s /q /f /a ".desktop.ini"
-
Open
cmd
and open the current folder -
run
delete.bat
by simply calling it incmd
Now you should be able to run
git remote set-head origin --auto
followed by git gc
answered May 27, 2022 at 21:44
1
rm .git/refs/remotes/origin/HEAD
git gc
answered Oct 13, 2022 at 10:26
If you’re using git worktrees, make sure you’re doing a
git worktree prune
before running
git gc
I had a worktree get corrupted and this seemed to do the trick after removing the corrupted worktree. git prune
by itself didn’t seem to work.
answered Dec 17, 2019 at 17:46
JeffPJeffP
3142 silver badges13 bronze badges
The cause of this for me was working in a compressed folder in Windows. When the folder was uncompressed, it corrupted the pack files, cascading other odd issues, such as not being able to prune nonexistent branches.
The only fix was to wipe out the working directory and clone the repo remote(s) again. Luckily, I could still push and pull updates to ensure nothing was lost. All is well now.
answered Jun 3, 2020 at 1:46
Will StrohlWill Strohl
1,6282 gold badges15 silver badges32 bronze badges
My problem occurred with a specific branch.
Apparently the reference file for branch was corrupted. I fixed it like that.
git checkout main
// I removed the file .gitrefsheadsbranch_xpto
git pull
git checkout branch_xpto
answered Feb 9, 2021 at 16:25
I ran into the same issue, when I tried to pull from the origin branch, I got the following error:
fatal: bad object refs/remotes/origin/account
The solutions above didn’t work for me for some reason. Kept getting this error
mv: cannot stat '.git/refs/remotes/origin/HEAD': No such file or directory
And running git gc
gave this error:
error: bad ref for .git/logs/refs/remotes/origin/account
fatal: bad object refs/remotes/origin/account
fatal: failed to run repack
In my situation, the remote branch was pointing to a branch that didn’t exist.
What fixed it for me was deleting the branch
git branch -D account
and also deleting it from .git/refs/remotes/origin/account
Everything working perfectly.
answered Jul 25, 2022 at 14:39
I have a problem with git on Windows Azure. Git status shows — «fatal: bad object HEAD» and I tried running:
git fsck --full
git gc
But git fsck
shows:
broken link from commit 739df633f185ce5d1ab7eb97d619b28e7d81185a
to tree 2a6d4876d135c1fa7cbe1348c62570006e895fc5
broken link from commit 9c7eae5ffed34dbfac977e515dee675626b59f93
to tree 400132d215ab9aced883a9971e648b82624b2032
broken link from commit 9c7eae5ffed34dbfac977e515dee675626b59f93
to commit 4a49af0a0cb64a0a0415734b11772d6df18561fb
broken link from commit bc3072f30e71c616a8196089e19a67a2c9c0a5ad
to tree 0aa813c183487d0a1b1f7ae81501ca7a1168283f
broken link from commit d3bb4f8545e91ec8ace15ad31a3147d92a1d4242
to tree 4682108accd8e72fe68858232386dffe60f9f02d
broken link from commit 6b34795c4b54286301bcdc0ed254a04c132cb2ad
to tree 5c57dd3222d11924dba841d3cae517bdc9220601
broken link from commit d70172d855391b93bc1c5eeb9b4226df525dfc6e
to commit 390c8cbd527c8e707c51e25142e54421f4dd3948
broken link from commit cc05e8d2e3733693ebb67d697ae4b65e51fea79a
to commit 32f081f8b901425fd1e8898478f0551970bee0f5
broken link from tree 6a75ed6d0311d800078e77f43d427d128372d5bc
to blob 4a064d610c0e7207967d59934c8bc5f491f26dae
broken link from tree 6a75ed6d0311d800078e77f43d427d128372d5bc
to tree 5c06ec964dcbade49287d0f36efe1f7b60f446e3
broken link from tree b4855fa6734b5652a93a9b799eafe47fad0d13a0
to blob 3e1fb421613dc9066cbf9c95eddc61619a9f8eed
broken link from tree b4855fa6734b5652a93a9b799eafe47fad0d13a0
to tree 556a50048d42346c283c94b78ea278ba1d57d251
broken link from tree 289c03409370c4ca7c12266ce2822a2976bd032b
to blob 3abf3c48ada45f63404dcf4d675ddfdadcfa83c6
broken link from tree 289c03409370c4ca7c12266ce2822a2976bd032b
to blob 3fa569892003b468ed1301426dd6d96d9644be3c
broken link from tree 289c03409370c4ca7c12266ce2822a2976bd032b
to blob 0a9a54a51e84f3bc34122dbce1146d895fcbe22c
broken link from tree 289c03409370c4ca7c12266ce2822a2976bd032b
to blob 3fa48873564361b4d95830803ae77f79eeafaf5b
git branch
shows — *master
Blaszard
30.4k47 gold badges151 silver badges230 bronze badges
asked Nov 28, 2013 at 10:49
dotnetrocksdotnetrocks
2,49912 gold badges36 silver badges54 bronze badges
3
try this; it worked for me (Warning: this destroys work that exists only in your local repo):
rm -rf .git
You can use mv
instead of rm
if you don’t want to lose your stashed commits
then copy .git from other clone
cp <pathofotherrepository>/.git . -r
then do
git init
this should solve your problem , ALL THE BEST
Nathan Long
121k96 gold badges331 silver badges441 bronze badges
answered Aug 17, 2017 at 8:45
8
Your repository is corrupt. That means data is lost that cannot be recovered by git itself. If you have another clone of this repository, you can recover the objects from there, or make a new clone.
fatal: bad object HEAD
means the branch referenced from HEAD is pointing to a bad commit object, which can mean it’s missing or corrupt.
From the output of git fsck
, you can see there are a few tree, blob and commit objects missing.
Note that using git itself is not enough to keep data safe. You still need to back it up in cases of corruption.
awatts
9886 silver badges13 bronze badges
answered Nov 28, 2013 at 10:55
IkkeIkke
97.9k23 gold badges96 silver badges120 bronze badges
1
This happened because by mistake I removed some core file of GIT. Try this its worked for me.
re-initialize git
git init
fetch data from remote
git fetch
Now check all your changes and git status by
git status
answered Jun 4, 2018 at 7:10
Mahesh GarejaMahesh Gareja
1,5422 gold badges12 silver badges23 bronze badges
3
Running
git remote set-head origin --auto
followed by
git gc
answered Jun 16, 2020 at 14:00
BillBill
4035 silver badges9 bronze badges
3
In my case the error came out of nowhere, but didn’t let me push to the remote branch.
git fetch origin
And that solved it.
I agree this may not solve the issue for everyone, but before trying a more complex approach give it a shot at this one, nothing to loose.
answered Apr 1, 2020 at 13:15
Felipe PereiraFelipe Pereira
11.1k4 gold badges39 silver badges45 bronze badges
3
Your repository is broken. But you can probably fix it AND keep your edits:
- Back up first:
cp your_repository your_repositry_bak
- Clone the broken repository (still works):
git clone your_repository your_repository_clone
- Replace the broken .git folder with the one from the clone:
rm -rf your_repository/.git && cp your_repository_clone/.git your_repository/ -r
- Delete clone & backup (if everything is fine):
rm -r your_repository_*
answered Dec 23, 2017 at 22:25
jan-glxjan-glx
6,9042 gold badges39 silver badges60 bronze badges
2
I had a similar problem and what worked for me was to make a new clone from my original repository
answered Sep 1, 2014 at 13:42
serupserup
5075 silver badges11 bronze badges
2
I managed to fix a similar problem to this when some of git’s files were corrupted:
https://stackoverflow.com/a/30871926/1737957
In my answer on that question, look for the part where I had the same error message as here:
fatal: bad object HEAD.
You could try following what I did from that point on. Make sure to back up the whole folder first.
Of course, your repository might be corrupted in a completely different way, and what I did won’t solve your problem. But it might give you some ideas! Git internals seem like magic, but it’s really just a bunch of files which can be edited, moved, deleted the same as any others. Once you have a good idea of what they do and how they fit together you have a good chance of success.
answered Jun 16, 2015 at 15:32
jwgjwg
5,3372 gold badges43 silver badges57 bronze badges
I solved this by doing git fetch. My error was because I moved my file from my main storage to my secondary storage on windows 10.
answered Sep 21, 2020 at 22:38
In my case, this happened because of a bad commit object.
For example,
ubuntu@server41:~/proj31$ git status -s | grep M
fatal: bad object HEAD
I had to copy the .git directory from the newly cloned in another directory(same repo) to the git repo that had this problem. (see below)
ubuntu@server41:~/proj31$ cd ..
ubuntu@server41:~$ mkdir newr
ubuntu@server41:~$ cd newr
ubuntu@server41:~/newr$ git clone https://github.com/account434/proj31.git
ubuntu@server41:~/newr$ cd
ubuntu@server41:~/newr$ cd proj31
# copy .git directory from newly clone(same repo) to the one which has this problem.
ubuntu@server41:~/proj31$ cp -r ../newr/proj31/.git .
And it worked.
answered Apr 14, 2022 at 7:00
SuperNovaSuperNova
24k6 gold badges90 silver badges62 bronze badges
Make a copy of your git dir in your local host and run git init
there once again. Push the project to a brand new reprository.
phd
77.7k12 gold badges112 silver badges152 bronze badges
answered Jul 15, 2017 at 10:56
I solved this by copying the branch data (with the errors) to my apple laptop local git folder.
Somehow in the terminal and when running: git status, tells me more specific data where the error occurs. If you look under the errors, hopefully you see a list of folders with error. In my case GIT showed the folder which was responsible for the error. Deleting that folder and commiting the branche, I succeeded. git status was working again
the other devices updating by git pull; everything working again on every machine.
Hopefully this will work for you also.
answered Sep 7, 2017 at 13:54
This is unlikely to be the source of your problem — but if you happen to be working in .NET you’ll end up with a bunch of obj/
folders. Sometimes it is helpful to delete all of these obj/
folders in order to resolve a pesky build issue.
I received the same fatal: bad object HEAD
on my current branch (master) and was unable to run git status
or to checkout any other branch (I always got an error refs/remote/[branch] does not point to a valid object
).
If you want to delete all of your obj
folders, don’t get lazy and allow .git/objects
into the mix. That folder is where all of the actual contents of your git commits go.
After being close to giving up I decided to look at which files were in my recycle bin, and there it was. Restored the file and my local repository was like new.
answered Jan 10, 2019 at 13:48
wdonahoewdonahoe
1,0131 gold badge11 silver badges22 bronze badges
This happened to me on a old simple project without branches. I made a lot of changes and when I was done, I couldn’t commit.
Nothing above worked so I ended up with:
- Copied all the code with my latest changes to a Backup-folder.
- Git clone to download the latest working code along with the working .git folder.
- Copied my code with latest changes from the backup and replaced the cloned code (not the .git folder).
- git add and commit works again and I have all my recent changes.
answered Mar 24, 2020 at 19:59
AndreasAndreas
7572 gold badges11 silver badges20 bronze badges
In my case I tried cloning from the remote repository to a new TEST local repository. Then used the new .git folder to replace the «corrupt» .git folder. Ran git status and could see the latest differences.
BEWARE: Check differences between your local folder and repo using git add . -v. To undo changes before commit use git reset. You may need to bring «deleted» files from the TEST local repository cloned in the beginning of this operation.
answered May 19, 2021 at 18:44
DavidDavid
1,04411 silver badges12 bronze badges
The solution by @jan-glx should always work. I am adding here step 3., which is needed in case you were working on a branch other than master/main:
- Back up first:
cp your_repository your_repositry_bak
- Clone the broken repository:
git clone your_repository your_repository_clone
- (if needed) Switch to your working branch in the cloned repo
cd your_repository_clone && git checkout your_working_branch
- Replace the broken .git folder with the one from the clone:
rm -rf your_repository/.git && cp your_repository_clone/.git your_repository/ -r
- (if everything is fine) Delete clone & backup:
rm -r your_repository_*
answered Dec 12, 2021 at 11:55
LolloLollo
152 bronze badges
I came across this issue when I used submodules
The file structure
-- Python.Hot
-----.git/
-----Python.OpticalTweezers/
-----Python.OpticalTweezersGUI/
-----.gitmodules
Question
when I checked the log of any submodule, I came across this issue.The waring message is «Could not open log. libgit reports:bad object xxxxxxx«
This issue doesn’t exist in the several versions at the very beginning.
snapshot
answered Jan 6, 2022 at 10:20
1
Problem
I had the problem where I had local changes preventing me from checking out the main branch, git status
would give me fatal: bad object HEAD
, and git stash
would give me BUG: diff-lib.c:607: run_diff_index must be passed exactly one tree
.
Solution
I found that I probably was on a pruned branch (I believe). Force checking out the main branch and then deleting that branch did the trick for me:
git checkout main -f
git branch -D <name_of_branch>
Note: I did do some juggling with a backup of my .git
-folder, re-cloning the original repository somewhere else, and overwriting the .git
folder temporarily to try to restore git functionality, but in the end the commands above was what saved me with my git history intact!
answered Mar 14, 2022 at 17:49
mlunoemlunoe
4,4124 gold badges33 silver badges43 bronze badges
Clone the repository to another directory then just delete corrupted .git folder and replace it with .git from clone. then running git init, git fetch and git status will auto detect the last uncommitted changes
answered Dec 5, 2022 at 6:20
ZahidZahid
4341 gold badge3 silver badges15 bronze badges
I solved this by renaming the branch in the file .git/refs/remotes/origin/HEAD
.
answered Mar 6, 2017 at 18:17
cemsbrcemsbr
331 silver badge4 bronze badges
1
Please excuse me if I’m not using the proper terminology since I’m barely knowledgeable in coding at the moment. I learned html and css a year ago to create my website, and after I created a github repository to make my site, I didn’t need to use any coding anymore (I just would paste my content in Atom, hit «Commit to master», and then «publish branch» and boom, my website would update with my content.) Anyways, a few months ago I started getting this error:
error: cannot lock ref 'refs/remotes/origin/master': unable to resolve reference 'refs/remotes/origin/master': reference broken From https://github.com/mihailovicm13/mihailovicm13.github.io ! [new branch] master -> origin/master (unable to update local ref)
I think this has something to do with the master being corrupted or something from what I’ve read — which can’t be very good..? Even though I got this message for months, I was still able to publish content to my site — I would press «publish branch» and get the error, but my content on my site would still somehow update. That was until this morning, when I made a change to my site and accidentally pressed «commit to master» on my GitHub Desktop app instead of doing it in Atom first. I didn’t think this would do anything, and I don’t know if it has anything to do with why I’m getting this error, but I get this when I press «publish branch»:
NEWER COMMITS ON REMOTE
«Desktop is unable to push commits to this branch because there are commits on the remote that are not present on your local branch. Fetch these new commits before pushing in order to reconcile them your local commits»
So I press «fetch», and it just takes me back to the error message I was already getting. So now I’m annoyed and trying to find solutions to my problem online. I found this question that was similar to mine: On git pull, “unable to resolve reference” and “Undefined error: 0”. On there, the dude tries the top answer in this thread: git pull fails “unable to resolve reference” “unable to update local ref”. Using this code:
$ git gc --prune=now $ git remote prune origin
Yields this:
error: bad ref for .git/logs/refs/remotes/origin/HEAD error: bad ref for .git/logs/refs/remotes/origin/master fatal: bad object refs/remotes/origin/HEAD fatal: failed to run repack
I didn’t know what to do, but I saw a guy in the comments say to delete the branch or something like that.. I don’t know if I should do that since its the «master» branch though, wouldn’t that mess everything up?
Сегодня я случайно наткнулся на это, пытаясь запустить Git сборщик мусора:
$ git gc
fatal: bad object refs/remotes/origin/HEAD
error: failed to run repack
Как мне с этим справиться?
10 ответов
Я не понимаю последствий этого, но, как предложено в этом поток , когда я столкнулся с этим, я просто сделал
$ mv .git/refs/remotes/origin/HEAD /tmp
(держите его на всякий случай), а затем
$ git gc
Работал без нареканий; Я не столкнулся с какими-либо проблемами.
265
Manos Nikolaidis
3 Май 2018 в 13:13
Увидев ответ Трентона, я посмотрел на свой .git/refs/remotes/origin/HEAD
и увидел, что он также указывает на старую ветку, которая теперь удалена.
Но вместо того, чтобы самому редактировать файл, я попробовал решение Райана:
git remote set-head origin --auto
Он автоматически установил файл в новую ветку, и после этого git gc
работал нормально.
123
WilQu
20 Апр 2018 в 17:44
Проблема, с которой я столкнулся (это та же проблема, о которой @Stavarengo упоминал в этот комментарий выше) заключается в том, что удаленная ветвь по умолчанию (develop
в моем случае) была удалена, но все еще упоминалась в .git/refs/remotes/origin/HEAD
.
Открытие .git/refs/remotes/origin/HEAD
в моем редакторе показало следующее:
ref: refs/remotes/origin/develop
Я тщательно отредактировал его, чтобы он указывал на мою новую ветку по умолчанию, и все было хорошо:
ref: refs/remotes/origin/master
Подсказка, которая подсказала мне, заключалась в том, что запуск git prune
показал эту ошибку:
> git prune
warning: symbolic ref is dangling: refs/remotes/origin/HEAD
107
Trenton
11 Сен 2017 в 19:08
Слава богу, я нашел это https://makandracards.com/chris-4/54101-fixing-a -git-репо
fatal: bad object refs/remotes/origin/HEAD
error: failed to run repack
Это может произойти, если восходящие ветки были удалены, и ваш источник указывает на них. Вы можете подтвердить это, запустив:
cat .git/refs/remotes/origin/HEAD
Если он указывает на несуществующую ветку, выполняется:
git remote set-head origin --auto
С последующим
git gc
Исправлю это
48
Thawinwats Uggaravisee
19 Апр 2021 в 16:15
Похоже, ваши символические ссылки могут быть сломаны… Попробуйте заменить его на ветку по умолчанию следующим образом: Например, моей веткой по умолчанию является master.
$ git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/master
$ git fetch --prune
$ git gc
Это должно исправить.
27
Conal Da Costa
17 Мар 2020 в 00:57
git update-ref -d [wrong reference here]
Это решит эту проблему.
Для вышеуказанной проблемы используйте следующий код:
git update-ref -d 'refs/remotes/origin/HEAD'
Если вы получаете ошибку с .git, как показано ниже:
error: bad ref for .git/logs/refs/remotes/origin/Dec/session-dynatrace-logs 6
Вы можете скопировать путь, начинающийся с refs, как показано ниже:
git update-ref -d 'refs/remotes/origin/Dec/session-dynatrace-logs 6'
4
Joshua Cleetus
18 Дек 2020 в 17:12
Причиной этого для меня была работа в сжатой папке в Windows. Когда папка была распакована, она повредила файлы пакета, что привело к другим странным проблемам, таким как невозможность удалить несуществующие ветки.
Единственное исправление состояло в том, чтобы стереть рабочий каталог и снова клонировать удаленные репозитории. К счастью, я все еще мог отправлять и получать обновления, чтобы ничего не было потеряно. Теперь все хорошо.
1
Will Strohl
3 Июн 2020 в 04:46
Моя проблема возникла с определенной веткой.
Видимо, справочный файл для ветки был поврежден. Я исправил так.
git касса главная
// Я удалил файл .gitrefsheadsbranch_xpto
git тянуть
git checkout branch_xpto
1
Rafael Pizao
9 Фев 2021 в 19:25
Я столкнулся с этой ошибкой, потому что ветвь по умолчанию была изменена с master
на main
. Я использовал смесь информации, предоставленной несколькими ответами выше, чтобы решить эту проблему:
cat .git/refs/remotes/origin/HEAD
Возвращается :
ref: refs/remotes/origin/master
Чтобы исправить это, я запустил:
git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/main
Я запустил это снова, чтобы перепроверить:
cat .git/refs/remotes/origin/HEAD
Который вернулся:
ref: refs/remotes/origin/main
Затем git gc
и git prune
работали нормально.
Чтобы увидеть, что происходит, я также пробовал:
git remote set-head origin --auto
Который вернулся:
origin/HEAD set to main
И это действительно решает проблему, автоматически идентифицируя реф.
1
Virtua Creative
10 Ноя 2021 в 15:26
Если вы используете рабочие деревья git, убедитесь, что вы делаете
git worktree prune
Перед запуском
git gc
У меня было повреждено рабочее дерево, и это, похоже, помогло после удаления поврежденного рабочего дерева. git prune
сам по себе не работает.
0
JeffP
17 Дек 2019 в 20:46
I randomly hit this today while trying to run Git garbage collect:
$ git gc
fatal: bad object refs/remotes/origin/HEAD
error: failed to run repack
How do I deal with this?
9 Answers
I don’t understand the ramifications of this, but as suggested in this thread, when I encountered this I just did
$ mv .git/refs/remotes/origin/HEAD /tmp
(keeping it around just in case) and then
$ git gc
worked without complaining; I haven’t run into any problems.
The problem that I ran into (which is the same problem that @Stavarengo mentioned in this comment above) is that the default remote branch (develop
in my case) had been deleted, but was still referenced in .git/refs/remotes/origin/HEAD
.
Opening .git/refs/remotes/origin/HEAD
in my editor showed this:
ref: refs/remotes/origin/develop
I carefully edited it to point at my new default branch and all was well:
ref: refs/remotes/origin/master
The clue that tipped me off was that running git prune
showed this error:
> git prune
warning: symbolic ref is dangling: refs/remotes/origin/HEAD
After seeing Trenton’s answer, I looked at my .git/refs/remotes/origin/HEAD
and saw that it was also pointing to an old branch that is now deleted.
But instead of editing the file myself, I tried Ryan’s solution:
git remote set-head origin --auto
It automatically set the file to the new branch, and git gc
worked fine after that.
Looks like your symbolic-refs might be broken…
Try the replacing it with your default branch like this:
For example, my default branch is master
$ git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/master
$ git fetch --prune
$ git gc
That should fix it.
Thank god I found this
https://makandracards.com/chris-4/54101-fixing-a-git-repo
fatal: bad object refs/remotes/origin/HEAD
error: failed to run repack
This may happen if upstream branches have been removed and your origin is pointing to it. You can confirm this by running:
cat .git/refs/remotes/origin/HEAD
If it is pointing to a branch that doesn’t exist, running:
git remote set-head origin --auto
followed by
git gc
will fix it
git update-ref -d [wrong reference here]
This will fix this issue.
For above issue use following code:
git update-ref -d 'refs/remotes/origin/HEAD'
In case you are getting error with .git like below:
error: bad ref for .git/logs/refs/remotes/origin/Dec/session-dynatrace-logs 6
You can copy the path starting from refs like below:
git update-ref -d 'refs/remotes/origin/Dec/session-dynatrace-logs 6'
The cause of this for me was working in a compressed folder in Windows. When the folder was uncompressed, it corrupted the pack files, cascading other odd issues, such as not being able to prune nonexistent branches.
The only fix was to wipe out the working directory and clone the repo remote(s) again. Luckily, I could still push and pull updates to ensure nothing was lost. All is well now.
If you’re using git worktrees, make sure you’re doing a
git worktree prune
before running
git gc
I had a worktree get corrupted and this seemed to do the trick after removing the corrupted worktree. git prune
by itself didn’t seem to work.
My problem occurred with a specific branch.
Apparently the reference file for branch was corrupted. I fixed it like that.
git checkout main
// I removed the file .gitrefsheadsbranch_xpto
git pull
git checkout branch_xpto
Детальное объяснение
Что означает сообщение об ошибке «Разбитая голова»?
Прежде чем решить проблему, мы должны сначала понять сообщение об ошибке.
Сообщение об ошибке говорит, что HEAD сломан! Какая ГОЛОВА? Голова означает нашу текущую ветку. Ошибка в основном означает, что ТЕКУЩАЯ ВЕТКА не работает.
Допустим, у нас есть такие ветки, как ab
, bb
, cb
и текущая ветка ab
филиал.
Когда мы запускаем эту команду ls .git/refs/heads
, посмотрим ab
, bb
, cb
, то есть файлы, содержащие хэш-значение, например 392b55ccd3ba02fe236148c5264f8ef1da
.
Всякий раз, когда мы фиксируем, это значение хеш-функции изменяется.
Вернемся к сообщению об ошибке «Голова сломана».
На самом деле это означает, что хеш-значение этой ветки НЕДЕЙСТВИТЕЛЬНО!
Как восстановить эту ошибку (возможно)?
Шаг 1: Внесите множество изменений без фиксации.
Шаг 2: Выключите компьютер всего через 1 секунду после внесения больших изменений.
Итак, git не смог обновить новый хэш, и теперь старый становится недействительным!
Как решить?
Просто удалите текущее значение хеша! Так просто!
Компания ab
это наша текущая ветвь, которая является нашей разбитой головой!
rm .git/refs/heads/ab
команда удалит файл ab, содержащий НЕДЕЙСТВИТЕЛЬНОЕ хеш-значение.
Если ветка является удаленной веткой (которая до этого помещается в репозиторий), то мы должны git pull --allow-unrelated-histories --ff origin ab
Если ветка локальная, продолжайте фиксацию.
Решено!
Здравствуйте!
Поставил Red Hat 6.2.Решил установить git из исходников.Все прошло нормально.
Добавил проект. но при использовании git log
вываливается fatal.Bad default revision ‘HEAD’.
Как с этим бороться?
Спасибо.
-
Вопрос заданболее трёх лет назад
-
10296 просмотров
Так а у вас есть хоть один коммит в репозитории? Такая ошибка может в этом случае появиться.
Пригласить эксперта
git-reflog —all должно помочь
-
Показать ещё
Загружается…
09 февр. 2023, в 15:02
12000 руб./за проект
09 февр. 2023, в 14:22
1500 руб./за проект
09 февр. 2023, в 13:58
2000 руб./за проект
Минуточку внимания
Commit allegedly succeeded but files are ignored and git-objects are corrupt
==========================================================
Hello,
I regularly work with MATLAB’s Source Control, for years, and all relevant GIT operations are available and successful.
However, I recently started another new project, and after a successful «Source Control» setup (adding and commiting by the «Source Control» interface, as I have always done before), the files immediately moved from normal green circles (expected commit sign) to dot sign (ignored), indicating that the project’s files were not properly commited.
In the below, I describe various error reports that I get, which relate to this problem.
What could have happened that caused this commit failure, and how can this be fixed?
What could be different from the normal procedure that always worked for me before
THANK YOU!
———————————————————
Related Errors Description:
** «Source Control —> Refresh Git Status» yields:
«Missing Unknown ……. «
** «Source Control —> Push» yields:
Unable to push to remote ‘origin’ at ….
src refspec ‘refs/heads/master’ does not match any existing object (-1×4)’
** The !git status command yields:
fatal: bad object HEAD
** The !git fetch command yields
fatal: git upload-pack: not our ref 0000000000000000000000000000000000000000
fatal: remote error: upload-pack: not our ref 0000000000000000000000000000000000000000
** The !git fsck —full command yields many such lines:
bad sha1 file: .git/objects/17/997a16efa1715247366cb39d410a47ca88d61c.tmp
and also:
error: refs/desktop.ini: invalid sha1 pointer 0000000000000000000000000000000000000000
error: refs/heads/desktop.ini: invalid sha1 pointer 0000000000000000000000000000000000000000
error: refs/heads/master: invalid sha1 pointer 55288f81110bf3b016a8c4020dc77609a3e3e292
error: refs/tags/desktop.ini: invalid sha1 pointer 0000000000000000000000000000000000000000
error: HEAD: invalid sha1 pointer 55288f81110bf3b016a8c4020dc77609a3e3e292
error: HEAD: invalid reflog entry 55288f81110bf3b016a8c4020dc77609a3e3e292
error: refs/heads/master: invalid reflog entry 55288f81110bf3b016a8c4020dc77609a3e3e292
error: bad ref for .git/logs/refs/heads/desktop.ini
error: bad ref for .git/logs/refs/desktop.ini
error: bad ref for .git/logs/desktop.ini
dangling tree 762bd76d7790b0422cb9a87fb43656023121b1bc
notice: No default references
** The !git ls-files command yields the list of all commited files.
Notes:
** The .git folders in both SandBox and Remote look ok.
** Both SandBox and Remote are on Google Drive. I have read that this should work.
** I tried several advices given for the situation (various git commands).
** .gitignore does NOT exclude any file yet
What could have happened, and how can this be fixed? What could be different from the normal procedure that always worked for me before
Thank you,
Regards.