经典 Git 练习:
-
自行创建一个远程仓库,并获取远程仓库的
url
。 -
克隆仓库到目录 a 中。
-
添加一个文件
hello-git
文件到仓库中,其文件内容为:hello git
。 -
将修改提交,并推送到远程仓库中。
-
创建一个名为
test-git
的分支,并在hello-git
文件未尾追加一行test git branch
的内容。将分支推送到远程仓库。 -
将分支
test-git
合并到master
分支中,并更新到远程仓库中。 -
制造一个文件冲突,并解决后更新到远程仓库中。
步骤:
1. 创建一个远程仓库
-
在你的服务器或本地创建一个空的 bare 仓库(通常用于远程仓库)。
mkdir my_remote_repo.git cd my_remote_repo.git git init --bare
-
获取远程仓库的 URL。本地创建的仓库 URL 类似于
file:///path/to/my_remote_repo.git
。服务器上,URL 类似于ssh://user@server:/path/to/my_remote_repo.git
。
2. 克隆仓库到目录 a 中
- 在本地机器上,克隆刚才创建的远程仓库到目录
a
中。git clone <remote-repo-url> a cd a
3. 添加一个文件并推送到远程仓库
-
在目录
a
中创建一个名为hello-git
的文件,并添加内容。echo "hello git" > hello-git git add hello-git git commit -m "Add hello-git file"
-
将更改推送到远程仓库。
git push origin master
4. 创建一个分支并推送到远程仓库
-
创建一个新的分支
test-git
。git checkout -b test-git
-
在
hello-git
文件末尾追加一行test git branch
的内容。echo "test git branch" >> hello-git git add hello-git git commit -m "Add test-git branch line to hello-git"
-
将
test-git
分支推送到远程仓库。git push origin test-git
5. 合并 test-git
分支到 master
分支并更新远程仓库
-
切换回
master
分支。git checkout master
-
合并
test-git
分支。git merge test-git
-
将合并后的
master
分支推送到远程仓库。git push origin master
6. 制造一个文件冲突并解决
-
在
master
分支上做一些改变(制造冲突)。echo "master change" >> hello-git git add hello-git git commit -m "Change in master"
-
切换到
test-git
分支,并在同一文件同一位置做其他改变。git checkout test-git echo "test-git change" >> hello-git git add hello-git git commit -m "Change in test-git"
-
切换回
master
分支并尝试合并test-git
,这将产生冲突。git checkout master git merge test-git
-
Git 会报告冲突,编辑
hello-git
文件手动解决冲突,然后添加并提交更改。# 解决冲突后 git add hello-git git commit -m "Resolve merge conflict between master and test-git"
-
将解决冲突后的
master
分支推送到远程仓库。git push origin master
这些步骤完成了从创建远程仓库、克隆、分支操作、合并以及解决冲突的完整 Git 操作流程。