Skip to content

Instantly share code, notes, and snippets.

@bhcleek
Last active November 6, 2022 11:09
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!!

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