HOWTO · Git
在 Git 上建立和使用分支
本教程介紹 Git 分支。我們將看到 Git 分支如何幫助你組織專案。
本教程介紹 Git 分支。我們將看到 Git 分支如何幫助你組織專案。
我們將處理的一些命令是 git branch 和 git checkout。
在 Git 中使用 git branch 命令建立、顯示和刪除分支
我們使用 git branch 命令來建立、顯示和刪除分支。
你不能使用該命令在不同的分支之間進行切換。
git branch顯示你的倉庫中的所有分支。git branch <branch name>在我們的倉庫中建立一個新分支<branch name>。git branch -d <branch name>刪除分支<branch name>。在執行此命令之前先合併更改。git branch -D <branch name>無一例外地刪除一個分支。當你對決定持肯定態度時,請使用此命令。git branch -m <branch name>重新命名或移動分支。
讓我們建立一個名為 New_Branch 的新分支。
pc@JOHN MINGW64 ~/Git (main)
$ git branch New_Branch
檢查分支是否存在。
pc@JOHN MINGW64 ~/Git (main)
$ git branch
New_Branch
* main
我們從上面的輸出中有兩個分支,New_Branch 和 main。
現在讓我們嘗試刪除 New_Branch。
pc@JOHN MINGW64 ~/Git (main)
$ git branch -d New_Branch
Deleted branch New_Branch (was 78129a6).
當你有未合併的更改時,你將收到一條錯誤訊息。使用 git push origin --delete <branch name> 從遠端倉庫中刪除分支。
使用 git checkout -b <branch> 建立具有當前 Git 更改的新分支
git checkout 命令在專案的分支之間切換。
要檢查倉庫中的現有分支,請使用 git checkout <branch>。下面是一個例子。
$ git branch
Last_Branch
New_Branch
* main
pc@JOHN MINGW64 ~/Git (main)
$ git checkout New_Branch
Switched to branch 'New_Branch'
M .bash_history
M text.txt.txt
M text.txt.txt.bak
在上面的程式碼中,我們有兩個分支,New_Branch 和 Last_Branch。我們使用 git checkout New_Branch 從我們的 main 分支切換到 New_Branch。
使用 git checkout -b <branch> 切換到新分支。讓我們看一個例子。
pc@JOHN MINGW64 ~/Git (New_Branch)
$ git checkout -b Branch1
Switched to a new branch 'Branch1'
當你切換到新分支時,Git 會自動將你當前分支的更改儲存到新分支。看一下這個。
pc@JOHN MINGW64 ~/Git (Branch1)
$ git status
On branch Branch1
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: .bash_history
modified: text.txt.txt
modified: text.txt.txt.bak
Untracked files:
(use "git add <file>..." to include in what will be committed)
.bash_history.bak
no changes added to commit (use "git add" and/or "git commit -a")
上面的輸出證明 Git 儲存了從 main 分支到 Branch1 的更改。