使用-orphan-参数创建独立空白分支

创建一个文件夹 testbranch,添加一个文件 main.txt。执行 git init 初始化,执行提交。此时 master 分支有了第一个提交记录:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
macName:testbranch userName$ git init
已初始化空的 Git 仓库于 /Users/userName/Desktop/testbranch/.git/
macName:testbranch userName$ git status
位于分支 master

尚无提交

未跟踪的文件:
(使用 "git add <文件>..." 以包含要提交的内容)
main.txt

提交为空,但是存在尚未跟踪的文件(使用 "git add" 建立跟踪)
macName:testbranch userName$ git add .
macName:testbranch userName$ git commit -m "init"
[master(根提交) cd00bbe] init
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 main.txt

随意修改一下文件内容,再作一次提交。此时查看 master 的提交状态,可以看到有两次提交:

1
2
3
4
5
6
7
macName:testbranch userName$ git add .
macName:testbranch userName$ git commit -m "again"
[master 9d01aa3] again
1 file changed, 1 insertion(+)
macName:testbranch userName$ git log --pretty=oneline -3
9d01aa3ed29dc9caa1b67175e1e2c7ce4db21712 (HEAD -> master) again
cd00bbe75405be350fd7c4cc06d4b304ababe8c5 init

此时新建一个分支,other-normal。使用 git branch -a 后可立刻看到新建的分支。再查看提交,发现与 master 是一致的:

1
2
3
4
5
6
7
8
macName:testbranch userName$ git checkout -b other-normal
切换到一个新分支 'other-normal'
macName:testbranch userName$ git branch -a
master
* other-normal
macName:testbranch userName$ git log --pretty=oneline -3
9d01aa3ed29dc9caa1b67175e1e2c7ce4db21712 (HEAD -> other-normal, master) again
cd00bbe75405be350fd7c4cc06d4b304ababe8c5 init

返回 master,使用 git checkout --orphan other-orphan 新建并切换到分支 other-orphan。再次使用 git branch -a,发现不能看到新建的分支。使用 git log 查看提交情况,发现当前确实在 other-orphan 分支上。

注意:使用 –orphan 参数建立的分支必须要有提交后,才真正创建。

1
2
3
4
5
6
7
8
9
macName:testbranch userName$ git checkout master
切换到分支 'master'
macName:testbranch userName$ git checkout --orphan other-orphan
切换到一个新分支 'other-orphan'
macName:testbranch userName$ git branch -a
master
other-normal
macName:testbranch userName$ git log
fatal: 您的当前分支 'other-orphan' 尚无任何提交

将 other-orphan 分支的 main.txt 文件改名为 orphan.txt 并提交,再次查看全部分支,已经可以看到 other-orphan,而且提交情况也是独立的,与 master 分支无关。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
macName:testbranch userName$ git status
位于分支 other-orphan

尚无提交

要提交的变更:
(使用 "git rm --cached <文件>..." 以取消暂存)
新文件: main.txt

尚未暂存以备提交的变更:
(使用 "git add/rm <文件>..." 更新要提交的内容)
(使用 "git restore <文件>..." 丢弃工作区的改动)
删除: main.txt

未跟踪的文件:
(使用 "git add <文件>..." 以包含要提交的内容)
orphan.txt

macName:testbranch userName$ git add .
macName:testbranch userName$ git commit -m "orphan init"
[other-orphan(根提交) c2533ce] orphan init
1 file changed, 1 insertion(+)
create mode 100644 orphan.txt
macName:testbranch userName$ git branch -a
master
other-normal
* other-orphan
macName:testbranch userName$ git log --pretty=oneline -3
c2533cec5738396e99510ff8566f002547e5e000 (HEAD -> other-orphan) orphan init