Git 操作——如何刪除本地分支和遠程分支

 

Git 操作——如何刪除本地分支和遠程分支

 

Git 操作——如何刪除本地分支和遠程分支

引言

在大多數情況下,刪除 Git 分支很簡單。這篇文章會介紹如何刪除 Git 本地分支和遠程分支。

用兩行命令刪除分支

// 刪除本地分支
git branch -d localBranchName

// 刪除遠程分支
git push origin --delete remoteBranchName

(譯者注:關於 git push 的更多介紹,請閱讀《git push 命令的用法》)。

什麼時候需要刪除分支

一個 Git 倉庫常常有不同的分支,開發者可以在各個分支處理不同的特性,或者在不影響主代碼庫的情況下修復 bug。

倉庫常常有一個 master 分支,表示主代碼庫。開發人員創建其他分支,處理不同的特性。

開發人員完成處理一個特性之後,常常會刪除相應的分支。

本地刪除分支

如果你還在一個分支上,那麼 Git 是不允許你刪除這個分支的。所以,請記得退出分支:git checkout master

通過 git branch -d <branch>刪除一個分支,比如:git branch -d fix/authentication

當一個分支被推送併合併到遠程分支後,-d 纔會本地刪除該分支。如果一個分支還沒有被推送或者合併,那麼可以使用-D強制刪除它。

這就是本地刪除分支的方法。

遠程刪除分支

使用這個命令可以遠程刪除分支:git push <remote> --delete <branch>

比如: git push origin --delete fix/authentication,這個分支就被遠程刪除了。

你也可以使用這行簡短的命令來遠程刪除分支:git push <remote> :<branch>,比如:git push origin :fix/authentication

如果你得到以下錯誤消息,可能是因爲其他人已經刪除了這個分支。

error: unable to push to unqualified destination: remoteBranchName The destination refspec neither matches an existing ref on the remote nor begins with refs/, and we are unable to guess a prefix based on the source ref. error: failed to push some refs to 'git@repository_name'

使用以下命令同步分支列表:

git fetch -p

-p 的意思是“精簡”。這樣,你的分支列表裏就不會顯示已遠程被刪除的分支了。

原文:How to Delete a Git Branch Both Locally and Remotely

 

https://www.freecodecamp.org/chinese/news/how-to-delete-a-git-branch-both-locally-and-remotely/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章