Skip to content

Instantly share code, notes, and snippets.

@bhcleek
Last active October 10, 2024 01:44
Show Gist options
  • Save bhcleek/5639080 to your computer and use it in GitHub Desktop.
Save bhcleek/5639080 to your computer and use it in GitHub Desktop.
recover lost index

to recover files that were added to the index but whose changes were lost (e.g. git reset --hard)

git fsck --unreachable | grep commit | cut -d\  -f3 | xargs git show
  1. git fsck --unreachable to get all the items that are unreachable
  2. grep commit to filter out all entries except for commits (the index will show up as a commit)
  3. cut -d\ -f3 to filter out all but the SHA1s
  4. xargs git show to show all of the contents of the objects.

Once you've identified the SHA1 that contains the changes that were lost, check it out to get the working tree back into the state of the index at the time git reset --hard was run.

git checkout -p <SHA1>

to apply the changes that were lost as a patch instead of replacing the tree wholesale, git apply can be used.

git apply <(git diff <SHA1>^ <SHA1>)
@HwangTaehyun
Copy link

You saved me.. Thank you!!

@mskiptr
Copy link

mskiptr commented Oct 10, 2024

Accidentally git added way too much and it was easier to look through fsck than think which changes should be reset. Though in my case I had to look at unreachable blobs (and not commits) instead. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment