During development, I stumbled upon an error in GIT that prevented me to complete any operation that required to contact remote origin (Fetch, push, etc..)

No matter which branch I was on, I would always received the following error when trying any of the above operations:

fatal: bad object HEAD

The repository in question was quite big ( over 4gb) and I wanted to find a solution that did not require me to pull a full copy of the repository down again.

The problem

The source of the issue, is a corrupted file within the GIT folder. There is no special reason for this to happen ( or at least I could not find any reasonable explanation for it), but it is not extremely common.

The code

I am going to share the solution that I have used in my specific case. It solved the issue in just a few seconds.

The following code, need to be run from the location of the affected repository.

cp .git/config .git/config.backup
git remote remove origin
mv .git/config.backup .git/config
git fetch

The explanation

The code above is self explanatory, but for the curious I will explain below line by line.

cp .git/config .git/config.backup

This line uses the command utility for copying files (read more). It is simply make a backup copy of the config file, within the .git folder

git remote remove origin

This line of code uses the remote feature of git, that has the main duty of
managing set of track repository. As explained on the official Git documentation , the remove command is used to remove all remote-tracking branches and configuration settings.

This last line of code, is the actual solution to our problem. By removing all configuration and existing files of remote branches, we remove our corrupted files.

mv .git/config.backup .git/config

We are not going to use another command utility, the one for moving files MV, as explained on the wikipedia website. The command is restoring our previously backed up config file. This step is needed to re-set all the remote branches.

git fetch

If you have ever used GIT, you will have come across the FETCH command. Running this command, will recreate all the files that we have previously removed. GIT is going to use the information within the config file, to know what branches and tags should be fetched from remote.

Conclusion

The above code helped me, and I hope it will support you in solving your issues. Please feel free to post any comment and/or suggestion to improve the above fix.

🤞 Don’t miss these tips!

No spam emails.. Pinky promise!