版本管理中实践中,对分支的操作是一个基本操作。本文通过一个小实验,给学员演示如何在Git中建立分支,如何切换分支,以及如何在本地和远程服务器间同步分支。
克隆项目
首先,从 GitHub 上克隆一个基础项目下来。
1
| git clone https://github.com/hhcx/git-study.git
|
系统显示:
1 2 3 4 5 6
| Cloning into 'git-study'... remote: Enumerating objects: 4, done. remote: Counting objects: 100% (4/4), done. remote: Compressing objects: 100% (3/3), done. remote: Total 4 (delta 0), reused 0 (delta 0), pack-reused 0 Unpacking objects: 100% (4/4), done.
|
完成后可以看到在当前目录中建立了一个新的目录: “git-study”, 进入目录后,可以看到从远处服务器上拿下来的两个文件: “LICENSE” 和 “README.md”
修改README.md并提交
打开 README.md 文件并在文件底部添加一行, “# start…”。修改后的文件内容如下:
1 2 3 4
| # git-study Learn the git command with simples
# start...
|
将修改提交到本地版本库
1 2
| git add README.md git commit -m "start..."
|
同步到远程库中
系统会提示需要输入账号和密码,输入以后就将本地的修改同步到远程了。
1 2 3 4 5 6 7 8 9 10
| Username for 'https://github.com': xxxx Password for 'https://xxxx@github.com': Enumerating objects: 5, done. Counting objects: 100% (5/5), done. Delta compression using up to 4 threads Compressing objects: 100% (3/3), done. Writing objects: 100% (3/3), 325 bytes | 325.00 KiB/s, done. Total 3 (delta 0), reused 0 (delta 0) To https://github.com/hhcx/git-study.git 42e90d1..5a4300a master -> master
|
建立分支
首先,查看本地已有的分支:
系统会显示已经存在本地的分支:
可以看到,在本地当前只有一个master分支。星号表示当前工作的分支
现在,加入新的分支: “B1”, 执行:
再次查看本地分支的情况:
系统显示:
可以看到,现在再本地已经有了”B1”和”master”两个分支,当前是工作在”master”分支下。
切换分支
通过 checkout 命令可以切换到不同的分支,比如:
1 2
| git-study stu$ git checkout B1 Switched to branch 'B1'
|
将本地工作区切换到B1分支。 通过 branch 命令,可以查看:
1 2 3
| git-study stu$ git branch * B1 master
|
修改分支中的文件
编辑 README.md 文件,在末尾加入一些内容,编辑以后的文件如下:
1 2 3 4 5 6 7 8
| # git-study Learn the git command with simples
# start...
## Branch 1(B1)
Add something.
|
现在将修改后的文件提交到本地, 执行:
1 2
| git add README.md git commit -m "B1,something"
|
系统提示:
1 2
| [B1 1d42bd8] B1,something 1 file changed, 3 insertions(+)
|
将分支同步到远程服务器
1
| git push --set-upstream origin B1
|
系统提示:
1 2 3 4 5 6 7 8 9 10 11 12 13
| Enumerating objects: 5, done. Counting objects: 100% (5/5), done. Delta compression using up to 4 threads Compressing objects: 100% (3/3), done. Writing objects: 100% (3/3), 354 bytes | 354.00 KiB/s, done. Total 3 (delta 0), reused 0 (delta 0) remote: remote: Create a pull request for 'B1' on GitHub by visiting: remote: https://github.com/hhcx/git-study/pull/new/B1 remote: To https://github.com/hhcx/git-study.git * [new branch] B1 -> B1 Branch 'B1' set up to track remote branch 'B1' from 'origin'.
|
现在,在远程库中已经加入了B1分支,因为我们在实验中使用的是 GitHub, 还可以之间在 GitHub 上查看,可以看到,切换不同的分支,README.md 显示的内容是不一样的。
从远程服务器获取一个特定的分支
1
| git clone -b B1 https://github.com/hhcx/git-study.git git-study_b1
|
系统提示:
1 2 3 4 5 6
| Cloning into 'git-study_b1'... remote: Enumerating objects: 10, done. remote: Counting objects: 100% (10/10), done. remote: Compressing objects: 100% (9/9), done. remote: Total 10 (delta 1), reused 5 (delta 0), pack-reused 0 Unpacking objects: 100% (10/10), done.
|
进入 git-study_b1 目录,查看 README.md 文件,可以看到文件是我们刚才提交在分支 B1 中的内容。你也可以进一步执行 git checkout 来切换分支。