git分支的学习

本文详细介绍如何使用Git进行分支管理,包括创建、切换、合并及删除分支等操作,并讲解了常见冲突解决方法及分支使用的最佳实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.查看分支

[root@localhost gitroot]# git branch
* master

创建分支(创建了一个lsk的分支)

[root@localhost gitroot]# git branch lsk

再次查看分支

[root@localhost gitroot]# git branch
  lsk
* master          ## *号表示在当前目录下

切换分支

[root@localhost gitroot]# git checkout lsk
D       2.txt
Switched to branch 'lsk'

新建一个2.txt,并加入上传到仓库

[root@localhost gitroot]# echo "lushuaizi" >2.txt
[root@localhost gitroot]# git 2.txt
git: '2.txt' is not a git command. See 'git --help'.
[root@localhost gitroot]# git add 2.txt
[root@localhost gitroot]# git commit -m"new file 2.txt"
[lsk 8d35751] new file 2.txt
 1 file changed, 1 insertion(+)
 create mode 100644 2.txt

查看当前分支下有哪些文件

[root@localhost gitroot]# ls
1.txt  2.txt

切换回分支master并查看只有1.txt

[root@localhost gitroot]# git checkout master
M       1.txt
Switched to branch 'master'
[root@localhost gitroot]# ls
1.txt

分支合并
把lsk合并到master

[root@localhost gitroot]# git merge lsk
Updating 17b6365..8d35751
Fast-forward
 2.txt | 1 +
 1 file changed, 1 insertion(+)
 create mode 100644 2.txt

分支冲突
在master分支下

[root@localhost gitroot]# cat 2.txt
lushuaizi
<<<<<<< HEAD
 add 2
=======
2
1
>>>>>>> lsk

在lsk分支下

[root@localhost gitroot]# cat 2.txt
lushuaizi
2
1

无法合并

[root@localhost gitroot]# git merge lsk
Auto-merging 2.txt
CONFLICT (content): Merge conflict in 2.txt
Automatic merge failed; fix conflicts and then commit the result.

解决方法:两个 文件内容修改为一致,重新合并

[root@localhost gitroot]# vi 2.txt
lushuaizi
2
1
~
[root@localhost gitroot]# git add 2.txt
[root@localhost gitroot]# git commit -m"2.txt"
[master 7c3cdc4] 2.txt
[root@localhost gitroot]# git merge lsk
Already up-to-date.

分支删除
在master分支下,可以删除lsk

[root@localhost gitroot]# git branch -d lsk
Deleted branch lsk (was 1e4e60d).

强制删除

[root@localhost gitroot]# git branch -D lsk

使用分支原则
① master分支是非常重要的,线上发布代码用这个分支,平时我们开发代码不要在这个分支上。
② 创建一个dev分支,专门用作开发,只有当发布到线上之前,才会把dev分支合并到master。
③ 开发人员应该在dev的基础上再分支成个人分支,个人分支(在自己PC上)里面开发代码,然后合并到dev分支。
在这里插入图片描述
查看远程分支命令为git ls-remote origin,可以看到所有分支。
在这里插入图片描述
git push分支分两种情况:
① 当本地分支和远程分支一致时
git push会把所有本地分支的变更一同推送到远程,如果想只推送一个分支,使用git push origin branch-name命令。
② 当本地分支比远程分支多
默认git push只推送本地和远程一致的分支,想要把多出来的本地分支推送到远程时,使用git push origin branch-name命令如果推送失败,先用git pull抓取远程的新提交。
在这里插入图片描述git clone的时候默认只把master分支克隆下来。如果想把所有分支都克隆下来,需要手动创建,在本地创建和远程分支对应的分支,使用git checkout -b branch-name origin/branch-name命令,需要注意本地和远程分支的名称要一致
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值