[GIT]如何删除分支【转载】

前言
在用git开发过程中,我们在分支合并后会将分支删除。这里我们会遇到两种情况,一是本地和远程的分支都还在,另一种就是远程仓库已经删除了,但本地仓库还有备份。

本地和远程分支都在
这是最常见的情况了,在这种情况下,我们会先删除本地分支,再删除远程分支。

1. 删除本地分支
在git中,删除本地分支并不会影响远程仓库中的任何分支。删除本地分支的命令:

git branch -d <local_branch>

先列出所有本地分支

1 $ git branch
2 * feature/test1
3 main

 

我们可以看到现在本地有两个分支,当前在<feature/test1>这个分支上。接下去我们要删除这个分支,就得先切换到其他分支

1 $ git checkout main
2 Switched to branch 'main'
3 Your branch is up to date with 'origin/main'.
4 $ git branch -d feature/test1
5 Deleted branch feature/test1.


注意,如果分支包含未合并的更改和未推送的提交,则该 -d标志将不允许删除本地分支。此时,如果你确定了不想要分支的内容,可以使用 -D替换 -d来强制删除此分支

现在我们再来看看分支情况:

1 $ git branch -a
2 * main
3 remotes/origin/HEAD -> origin/main
4 remotes/origin/feature/test1
5 remotes/origin/main

 

此时我们已经成功删除了本地仓库<feature/test1>,但我们之前有推送过分支到远程仓库,从上面列表可知,远程仓库中还存在此分支,那我们还需要删除远程仓库中的分支。

2. 删除远程分支
删除远程分支的命令:

git push <remote_name> -d <remote_branch>

  

先列出所有远程分支:

1 $ git branch -r
2 origin/HEAD -> origin/main
3 origin/feature/test1
4 origin/main

 

我们可以看到,此时远程仓库有<origin/feature/test1>和<origin/main>两个分支

origin/HEAD并非分支,它指向远程服务器上的默认分支,即为origin的远程仓库中的HEAD,一般此值的指向不会改变,具体请另行Google。

1 $ git push origin -d feature/test1
2 To https://github.com/***/git-practice.git
3 - [deleted] feature/test1

 

这时候再看看分支情况

$ git branch -a
* main
remotes/origin/HEAD -> origin/main
remotes/origin/main

 

可以看到我们已经成功删除了本地和远程仓库中的分支。此时,去Github上查看时,分支也已经删除。

清理远程仓库已经删除的分支
有时候因为操作不当,直接在远程仓库中删除了分支,而本地仓库还保留着原来的远程分支副本。此时再用git push <remote_name> -d <remote_branch>删除分支会提示错误:

1 $ git branch -a
2 * feature/test2
3 main
4 remotes/origin/HEAD -> origin/main
5 remotes/origin/feature/test2
6 remotes/origin/main


此时,我们去Github上直接删除<feature/test2>这个分支,然后再同前文一样进行分支删除。

 1 $ git branch -d feature/test2
 2 Deleted branch feature/test2
 3 
 4 $ git push origin -d feature/test2
 5 error: unable to delete 'feature/test2': remote ref does not exist
 6 error: failed to push some refs to 'https://github.com/***/git-practice.git'
 7 
 8 $ git branch -a
 9 * main
10 remotes/origin/HEAD -> origin/main
11 remotes/origin/feature/test2
12 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

至此我们已经成功清理掉远程已经删除的分支在本地的缓存。

posted @ 2023-07-12 11:30  ysx_小鱼  阅读(261)  评论(0编辑  收藏  举报