Git Recover Deleted or Staged Files

I ran into a situation where I accidentally staged a file I didn’t want to stage, and when I ran “git reset –hard” it was wiped out. After a simple google search (git recover staged files), recovering the file was simple.  I’ve put together a loop, which will check each commit, and look for a string “responsive”, which I know is in the file.

git fsck --lost-found | cut -f 3 -d ' ' | \
  while read -r commit; do 
    git show $commit | grep responsive; 
    if [ $? -eq 0 ]; then 
      echo $commit; 
    fi; 
  done

The response was…

rm -rf web/src/main/webapp/responsive/.sass-cache/
53fcd5f117f8e19243dfcde24c14524dc99b4c1e

I then just showed the commit blob with…

git show 53fcd5f117f8e19243dfcde24c14524dc99b4c1e
#!/bin/bash

cp -r /media/mount/* web/src/main/webapp/
rm -rf web/src/main/webapp/lost+found/
rm -rf web/src/main/webapp/responsive/.sass-cache/
find web/ -name '._*' | while read -r filename; do 
 rm -f "$filename"
done
rm -rf web/src/main/webapp/META-INF/
git status
Posted in git