前言
在用git开发过程中,我们在分支合并后会将分支删除。这里我们会遇到两种情况,一是本地和远程的分支都还在,另一种就是远程仓库已经删除了,但本地仓库还有备份。
本地和远程分支都在
这是最常见的情况了,在这种情况下,我们会先删除本地分支,再删除远程分支。
1. 删除本地分支
在git中,删除本地分支并不会影响远程仓库中的任何分支。删除本地分支的命令:
git branch -d <local_branch>
先列出所有本地分支
$ git branch * feature/test1 main
讯享网
我们可以看到现在本地有两个分支,当前在<feature/test1>这个分支上。接下去我们要删除这个分支,就得先切换到其他分支
讯享网$ git checkout main Switched to branch 'main' Your branch is up to date with 'origin/main'. $ git branch -d feature/test1 Deleted branch feature/test1.
注意,如果分支包含未合并的更改和未推送的提交,则该
-d标志将不允许删除本地分支。此时,如果你确定了不想要分支的内容,可以使用-D替换-d来强制删除此分支
现在我们再来看看分支情况:
$ git branch -a * main remotes/origin/HEAD -> origin/main remotes/origin/feature/test1 remotes/origin/main
此时我们已经成功删除了本地仓库<feature/test1>,但我们之前有推送过分支到远程仓库,从上面列表可知,远程仓库中还存在此分支,那我们还需要删除远程仓库中的分支。
2. 删除远程分支
删除远程分支的命令:
git push <remote_name> -d <remote_branch>
先列出所有远程分支:

讯享网$ git branch -r origin/HEAD -> origin/main origin/feature/test1 origin/main
我们可以看到,此时远程仓库有<origin/feature/test1>和<origin/main>两个分支
origin/HEAD并非分支,它指向远程服务器上的默认分支,即为origin的远程仓库中的HEAD,一般此值的指向不会改变,具体请另行Google。
$ git push origin -d feature/test1 To https://github.com/*/git-practice.git - [deleted] feature/test1
这时候再看看分支情况
$ git branch -a * main remotes/origin/HEAD -> origin/main remotes/origin/main
可以看到我们已经成功删除了本地和远程仓库中的分支。此时,去Github上查看时,分支也已经删除。
清理远程仓库已经删除的分支
有时候因为操作不当,直接在远程仓库中删除了分支,而本地仓库还保留着原来的远程分支副本。此时再用git push <remote_name> -d <remote_branch>删除分支会提示错误:
$ git branch -a * feature/test2 main remotes/origin/HEAD -> origin/main remotes/origin/feature/test2 remotes/origin/main
此时,我们去Github上直接删除<feature/test2>这个分支,然后再同前文一样进行分支删除。
$ git branch -d feature/test2 Deleted branch feature/test2 $ git push origin -d feature/test2 error: unable to delete 'feature/test2': remote ref does not exist error: failed to push some refs to 'https://github.com/*/git-practice.git' $ git branch -a * main remotes/origin/HEAD -> origin/main remotes/origin/feature/test2 remotes/origin/main
当我们查看分支时,可以看到<remotes/origin/feature/test2>还是存在的。此时,我们以下命令查看远程分支和本地的对应关系:
git remote show <remote_name>
$ git remote show origin * remote origin Fetch URL: https://github.com/*/git-practice.git Push URL: https://github.com/*/git-practice.git HEAD branch: main Remote branches: main tracked refs/remotes/origin/feature/test2 stale (use 'git remote prune' to remove) Local branch configured for 'git pull': main merges with remote main Local ref configured for 'git push': main pushes to main (up to date)
我们可以看到main分支的状态是tracked,而feature/test2的状态是stale,并且后面git已经提示了处理方式(use ‘git remote prune’ to remove)。
$ git remote prune origin Pruning origin URL: https://github.com/*/git-practice.git * [pruned] origin/feature/test2 $ git branch -a * main remotes/origin/HEAD -> origin/main remotes/origin/main
至此我们已经成功清理掉远程已经删除的分支在本地的缓存。
本文仅用于本人学习笔记之用,部分内容来源网上,如有侵权,请联系博主删除。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/23484.html