20.创建分支

在 Git 中,分支是指针,它指向某个提交记录。在 Git 存储库中,默认情况下有一个名为 master 的主分支,该分支指向最新的提交记录。

使用分支可以轻松地将代码库分成不同的版本,并在这些版本之间进行切换和合并操作。例如,如果你想尝试新功能或修复错误,可以创建一个新分支,在该分支上进行更改,而不会影响主分支。一旦更改准备好,就可以将其合并回主分支中。这使得协作变得更加容易,因为团队成员可以在自己的分支上开发新功能,而不必担心与其他人的更改冲突。

创建一个新分支

创建一个名为 lgnew 的新分支

# 新建分支
$ git checkout -b lgnew
   Switched to a new branch 'lgnew'

# 查看状态
$ git status
On branch lgnew
nothing to commit, working tree clean

git checkout -bgit branch <branchname>git checkout <branchname> 两个命令的快捷方式。

在此分支上新建一个文件并提交

我们在 lab 目录下,新建一个 test2.txt 文件,并提交

# 暂存
git add .\lab\test2.txt
# 提交
$ git commit -m "Added teset2.txt"
[lgnew ead2515] Added teset2.txt
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 lab/test2.txt
# 查看状态
$ git status
On branch lgnew
nothing to commit, working tree clean

切换主分支,创建一个新文件并提交

我们可以发现,我们在 lgnew 分支上的修改,并没有在主分支上显示。

# 切换主分支
git checkout master

# 查看状态
git status

# 暂存
git add .\lab\test3.txt

# 提交
git commit -m "Added teset3.txt"
[master da0a6f8] Added teset3.txt
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 lab/test3.txt

查看提交日志

git hist --all
* 1c78eab 2023-05-05 | Added teset3.txt (HEAD -> master) [aku]
| * 3d99c8f 2023-05-05 | Added teset2.txt (lgnew) [aku]
|/
* 5dc8b1e 2023-05-05 | Added .gitignore [aku]
* b77158a 2023-05-05 | Moved test.txt to lab [aku]
* 929f644 2023-05-05 | Added 123456 to the test.txt [aku]
| * 739560c 2023-05-05 | Oops,an error committed (tag: oops) [aku]
| * 1ca1854 2023-05-05 | Revert "Added 123 to the test.txt" [aku]
| * 375f4fe 2023-05-05 | Added 123 to the test.txt [aku]
|/
* d7f681f 2023-05-05 | Added abc to the test.txt (tag: v1) [aku]
* 01b8702 2023-05-05 | Add first file (tag: v1-beta) [aku]

Last updated