在 Git 上创建和使用分支

本教程介绍 Git 分支。我们将看到 Git 分支如何帮助你组织项目。

我们将处理的一些命令是 git branchgit checkout

在 Git 中使用 git branch 命令创建、显示和删除分支

我们使用 git branch 命令来创建、显示和删除分支。

你不能使用该命令在不同的分支之间进行切换。

  1. git branch 显示你的仓库中的所有分支。
  2. git branch <branch name> 在我们的仓库中创建一个新分支 <branch name>
  3. git branch -d <branch name> 删除分支 <branch name>。在运行此命令之前先合并更改。
  4. git branch -D <branch name> 无一例外地删除一个分支。当你对决定持肯定态度时,请使用此命令。
  5. 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_Branchmain

现在让我们尝试删除 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_BranchLast_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 的更改。