Search code examples
gitgit-worktree

How can I recover a staged changes from a deleted git worktree?


I accidentally deleted a worktree, with staged, but uncommitted changes! But git worktree list still shows the worktree (i.e., it hasn't been pruned)

Say,

/home/me/worktreeexample            0d4f25f [fix/something]
/home/me/                           0fd8c7e [master]

But because I just ran rm -rf worktreeexample/ there is nothing there $ ls worktreeexample/


Solution

  • Create a new file in worktreeexample telling git where to look. The format is based on the contents of .git/worktrees.

    So, for the example above, this will work:

    echo "gitdir: /home/me/.git/worktrees/worktreeexample" > worktreeexample/.git
    

    Then running git status in worktreeexample/ will show all your deleted files, and hopefully also your work in progress to be committed. Run

    cd worktreeexample
    git checkout -- .
    

    which will leave only the staged changes.

    Note if you have unstaged changes and you destroyed the working directory, you are out of luck.