Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

git

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.

like image 685
ssgao Avatar asked Oct 16 '25 15:10

ssgao


2 Answers

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
    
like image 163
Makoto Avatar answered Oct 19 '25 05:10

Makoto


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).

like image 39
wisbucky Avatar answered Oct 19 '25 05:10

wisbucky