Can I recover a branch after its deletion in Git?

后端 未结 20 2452
广开言路
广开言路 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:40

    Make sure to perform all of this locally, and confirm your repo is in the state you desire before pushing to Bitbucket Cloud. It may also be a good idea to clone your current repo, and test these solutions out first.

    1. If you just deleted the branch, you'll see something like this in your terminal:
        Deleted branch  (was )
    

    2.To restore the branch, use:

        git checkout -b  
    

    If you don't know the 'sha' off the top of your head, you can:

    1. Find the 'sha' for the commit at the tip of your deleted branch using:
        git reflog
    
    1. To restore the branch, use:
        git checkout -b  
    

    If your commits are not in your reflog:

    1. You can try recovering a branch by reseting your branch to the sha of the commit found using a command like:
        git fsck --full --no-reflogs --unreachable --lost-found | grep commit | cut -d\  -f3 | xargs -n 1 git log -n 1 --pretty=oneline > .git/lost-found.txt
    

    2.You can then display each commit using one of these:

        git log -p 
        git cat-file -p 
    

提交回复
热议问题