Can I recover a branch after its deletion in Git?

后端 未结 20 2339
广开言路
广开言路 2020-11-22 05:53

If I run git branch -d XYZ, is there a way to recover the branch? Is there a way to go back as if I didn\'t run the delete branch command?

20条回答
  •  执笔经年
    2020-11-22 06:28

    I rebased a branch from remote to try to clear a few commits I didn't want and was going to cherrypick the right ones that I wanted. Of course I wrote the SHAs wrong...

    Here is how I found them (mostly an easier interface/interaction from things on answers here):

    First, generate a list of loose commits in your log. Do this as soon as possible and stop working, as those may be dumped by the garbage collector.

    git fsck --full --no-reflogs --unreachable --lost-found > lost
    

    This creates a lost file with all the commits you will have to look at. To simplify our life, let's cut only the SHA from it:

    cat lost | cut -d\  -f3 > commits
    

    Now you have a commits file with all the commits you have to look.

    Assuming you are using Bash, the final step:

    for c in `cat commits`; do  git show $c; read; done
    

    This will show you the diff and commit information for each of them. And wait for you to press Enter. Now write down all the ones you want, and then cherry-pick them in. After you are done, just Ctrl-C it.

提交回复
热议问题