git命令之玩转checkout

创建和切换分支

git checkout最为常用的两种情形是创建分支和切换分支

可以基于远端分支和本地分支创建一个新的本地分支。

# git branch new_branch_name [本地分支名|远端分支名|commitID]
# git checkout new_branch_name
# 相当于上面两条命令的结合
git checkout -b new_branch_name [本地分支名|远端分支名|commitID]
# B 的意思是强制创建新的分支,即如果有同名分支,则覆盖之
git checkout -B new_branch_name [本地分支名|远端分支名|commitID]

切换分支

# 正常切换分支
git checkout <branch>


# git stash
# git checkout <branch>
# git stash pop
# 切换分支的时候,将当前分支的修改带走,相当于上面面的三条命令
git checkout --merge <branch>

切换到游离状态

切换到分支的游离状态,默认以该分支下的最后一次提交ID。git checkout --datch <branch> [本地分支名|远端分支名|commitID]

git checkout --detach
#  HEAD is now at 52acd56... 替换主页logo
git br
#  * (HEAD detached at 52acd56)
#  master
#  test
git checkout --detach origin/feature
#  Previous HEAD position was 52acd56... 替换主页logo
#  HEAD is now at c330d53... 产品logo
git br
#  * (HEAD detached at origin/feature)
#  master
#  test

创建无历史分支

假如某个分支上,积累了无数次的提交,commit message乱七八糟,那么这个命令将会拯救你,它会基于当前所在分支新建一个内容都在,但是没有任何的提交历史的分支。
新建的分支,严格意义上说,还不是一个分支,因为HEAD指向的引用中没有commit值,只有在进行一次提交后,它才算得上真正的分支。

git br -av
# * master e6e7a58 init index.html
git log --oneline
# e6e7a58 init index.html
# f337474 init index.css
# 5b308c2 init index.js
git checkout --orphan test master
# Switched to a new branch 'test'
git log
# fatal: your current branch 'test' does not have any commits yet
git br -av
#   master e6e7a58 init index.html
git st
# On branch test
# Initial commit
# Changes to be committed:
#   (use "git rm --cached <file>..." to unstage)
# 
# 	new file:   index.css
# 	new file:   index.html
# 	new file:   index.js
# 
git add .
git commit -m "新的无历史分支"
# [test (root-commit) 602b89e] 新的无历史分支
#  3 files changed, 0 insertions(+), 0 deletions(-)
#  create mode 100644 index.css
#  create mode 100644 index.html
#  create mode 100644 index.js
git br -av
#   master e6e7a58 init index.html
# * test   602b89e 新的无历史分支

检出文件

git checkout [本地分支名|远端分支名|commitID] [--] [<paths>] ...
主要用于覆盖工作区中对应的文件。

  • 如果省略commitID,则会用暂存区的文件覆盖工作区中的文件,否则用指定提交中的文件覆盖暂存区和工作区中的对应文件。
  • 如果省略 paths 则覆盖所有文件
# 双划线的意思后面的参数是 path 而不是 commitID
# 从当前分支暂存区中检出文件,覆盖工作区的内容。
git checkout -- <paths> ...
# 从指定 commitID 检出指定文件,覆盖暂存区和工作区中的对应文件
git checkout commitID -- <paths> ...

代码冲突,但是你很清楚该保留哪个分支的代码,可以使用如下方式解决冲突。

# 使用当前分支
git checkout [分支|commitID] --ours <conflict file>  
# 使用合并分支内容  
git checkout [分支|commitID] --theirs <conflict file>   
# 表示所有冲突文件都使用当前分支,--theirs同理
git checkout [分支|commitID] --ours .     
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值