先在本地使用 git branch -a
查看所有分支。
main
* v0.0.1
remotes/origin/HEAD -> origin/main
remotes/origin/main
remotes/origin/v0.0.1
一般结果如下,带有 remotes
路径的分支,为远程分支,可以看到本地两个分支,远程两个,现在我们要删除 v0.0.1
分支,方法如下:
先删除远程分支 remotes/origin/v0.0.1
,命令如下:
$ git push origin --delete v0.0.1
To https://github.com/<username>/<reponame>
- [deleted] v0.0.1
使用 git branch -a
查看所有分支:
$ git branch -a
* main
v0.0.1
remotes/origin/HEAD -> origin/main
remotes/origin/main
远程 v0.0.1
分支已经消失了,此时去远程仓库(比如 GitHub)查看,v0.0.1
分支也已经被删除了。
再使用删除本地 v0.0.1
分支,命令如下:
$ git branch -d v0.0.1
Deleted branch v0.0.1 (was a8eda0a).
再次使用 git branch -a
查看所有分支:
$ git branch -a
* main
remotes/origin/HEAD -> origin/main
remotes/origin/main
本地 v0.0.1
分支也消失了。
常见错误
无法删除分支 ,如下:
$ git branch -d v0.0.1
error: Cannot delete branch 'v0.0.1' checked out at 'C:/<username>/<reponame>'
一般这种情况,是没有退出所在分支。如果你还在 v0.0.1
分支上,那么 Git 是不允许你删除这个分支的。
使用 git branch -a
查看所在分支:
$ git branch -a
main
* v0.0.1
remotes/origin/HEAD -> origin/main
remotes/origin/main
*
星标所在为当前分支,当前分支为 v0.0.1
,所以无法删除 v0.0.1
分支。
使用 git checkout
切换分支:
$ git checkout main
Switched to branch 'main'
Your branch is up to date with 'origin/main'.
git branch -a
* main
v0.0.1
remotes/origin/HEAD -> origin/main
remotes/origin/main
当前正在 main
分支,即可删除 v.0.0.1
分支了。
$git branch -d v0.0.1
Deleted branch v0.0.1 (was a8eda0a).
如果一个分支还没有被推送或者合并,那么可以使用 -D
强制删除它。
$ git branch -D v0.0.1
Deleted branch v0.0.1 (was a8eda0a).