Can I recover a branch after its deletion in Git?

后端 未结 20 2097
广开言路
广开言路 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 06:29

    The top voted solution does actually more than requested:

    git checkout 
    git checkout -b 
    

    or

    git checkout -b  
    

    move you to the new branch together with all recent changes you might have forgot to commit. This may not be your intention, especially when in the "panic mode" after losing the branch.

    A cleaner (and simpler) solution seems to be the one-liner (after you found the with git reflog):

    git branch  
    

    Now neither your current branch nor uncommited changes are affected. Instead only a new branch will be created all the way up to the .

    If it is not the tip, it'll still work and you get a shorter branch, then you can retry with new and new branch name until you get it right.

    Finally you can rename the successfully restored branch into what it was named or anything else:

    git branch -m  
    

    Needless to say, the key to success was to find the right commit , so name your commits wisely :)

提交回复
热议问题