ssgao
ssgao

Reputation: 5521

How to undo 'git checkout -f' to get back uncommitted changes

I accidentally typed git checkout -f because I was trying to recover deleted file, but now all the uncommitted files are gone... that's a day of work... Is there a way to get it back? Thanks.

Upvotes: 4

Views: 4477

Answers (3)

wisbucky
wisbucky

Reputation: 37837

Two options:

  1. Check the git stash to see if you had stashed any of those files previously:

    git stash list
    git stash show stash@{0}
    
  2. If you had added/staged the files previously, you can try git fsck --lost-found. Git will save all the dangling blobs to ./git/lost-found/other directory (although they will not have their original filenames).

Upvotes: 2

Makoto
Makoto

Reputation: 106430

You've got about a snowball's chance sitting outside of Dante's Inferno for this one, but it hinges on one very important step.

You have to have run git add to those files at some point prior to this.

Otherwise, you're not going to have a good time.

If you have, then you can run git fsck --lost-found to recover any files that you've removed. What you'll get isn't the exact file name, but a dangling commit blob to it.

makoto@LATLON-Undefined:~/Desktop/smoketest$ echo "Goodbye file" > badfile.txt
makoto@LATLON-Undefined:~/Desktop/smoketest$ git status
On branch master
Untracked files:
  (use "git add <file>..." to include in what will be committed)

    badfile.txt

nothing added to commit but untracked files present (use "git add" to track)
makoto@LATLON-Undefined:~/Desktop/smoketest$ git add .
makoto@LATLON-Undefined:~/Desktop/smoketest$ git reset --hard HEAD
HEAD is now at 7124f25 Initial
makoto@LATLON-Undefined:~/Desktop/smoketest$ git status
On branch master
nothing to commit, working directory clean
makoto@LATLON-Undefined:~/Desktop/smoketest$ git fsck --lost-found
Checking object directories: 100% (256/256), done.
dangling blob 4a503984f4847abd45f4d795d1b74c6482164dcb

None of these blobs have any file information attached to them; namely, what file name they are. But they're still your data.

Depending on what you've got on your hands, you could do one of two things:

  • Enter into each dangling blob and manually try to derive the file name for it, or
  • In reference from this site, you could experiment with their Bash script to pull in all dangling blobs and place them into your current directory with their hash as the file name.

    I haven't personally tested this script, but he does show a video of it working.

    for blob in $(git fsck --lost-found | awk '$2 == "blob" { print $3 }');
        do git cat-file -p $blob > $blob.txt;
    done
    

Upvotes: 6

Carl Norum
Carl Norum

Reputation: 224944

Do you have a backup system that's tracking file modifications? You could get it back from there. Otherwise you're out of luck - commit more often!

Upvotes: 1

Related Questions