Git Recovery Guide

You have two commands available to you that can help you solve this:

git reflog

This is the easier way. But might not work.

git reflog shows a log of the references you have checked out in the past. It helps you retrace your steps. This can be helpful for figuring out the changes and locating lost commits. It’s my first resort during these kind of situations.

Run:

git reflog > reflog.txt

Inspect reflog.txt, you will see the SHAs of commits. Lines with moving from might help you when you transition to the commit you’re looking for.

Running git reflog {branchName} might do this searching process faster for you.

git fsck

You must be here if git reflog did not work for you.

Welcome to the club.

git fsck stands for “file system check” and it verifies the integrity of the version history in Git. This command checks the connectivity and validity of objects in the Git database.

Take a Deep Breath

Yes, you’re about 15% screwed. Take a deep breath. Remember, everyone’s messed up a commit or two, or ten (if it’s me)…

Extract All Possible SHAs

Start by extracting all the SHAs that git still remembers and store them in a file called all-shas.txt:

git fsck --full --no-reflogs --unreachable --dangling \
  | awk '{print $3}' \
  | sort \
  | uniq \
  > all-shas.txt

This command performs an integrity check and outputs the SHA of every object it finds, sorting and ensuring uniqueness of these SHAs before saving them to a file.

Create and Setup the Search Script

Now, let’s create a script to search through all these commits. Start by creating a file called find.sh and giving it execute permissions:

touch find.sh
chmod +x find.sh

Now, add the following content to find.sh:

#!/bin/bash

pattern="your-search-pattern" # Replace with your pattern

while IFS= read -r sha; do
    if git show "$sha" | grep -Eq "$pattern"; then
        commit_date=$(git show -s --format=%ci "$sha" 2>/dev/null) || commit_date='N/A'
        echo "Pattern found in commit $sha ($commit_date)"
        git log -1 --pretty=format:"%s" "$sha"
        echo "---------------------------------"
    fi
done < all-shas.txt

Make sure to replace your-search-pattern with a phrase or keyword that you remember from the lost commit.

Run the Search Script

Execute the find.sh script and redirect its output to a file for easier inspection:

./find.sh > found.txt

Inspect the Results

Open and review the found.txt file. This file will have the details of all the commits that match the given pattern.

This file will have the details of all the commits that match the given pattern.

Celebrate… Or Not?

Crack open that found.txt. If you find your lost work, feel free to reward yourself with scheduled back-ups. If not, consider whether this the universe’s way of saying you should have backed up.

Good luck and happy (or not so happy) recovering!