git checkout
的主要作用是 切换代码快照,可以是分支、标签、提交等。
请务必记得 git checkout — <file>
是一个危险的命令。 你对那个文件在本地的任何修改都会消失——Git 会用最近提交的版本覆盖掉它。 除非你确实清楚不想要对那个文件的本地修改了,否则请不要使用这个命令。
git checkout <branchname> 切换到分支
假设当前 HEAD指针 指向 master,而还存在一个 testing 分支指针。
git checkout testing
会使HEAD指针指向 testing:
此时再做新的提交时,会推进 testing 分支而 master 分支保留指向原提交对象:
当再次切换回 master 分支时,会将当前工作区重置为 master 分支所指向的提交对象的内容版本。
通常我们会在创建一个新分支后立即切换过去,这可以用 git checkout -b <newbranchname>
一条命令搞定。
git checkout — <filename> 回滚文件到上次提交的版本
在 Git 2.23版本之后推荐使用 git restore 来实现。
未暂存区域是这样:
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: CONTRIBUTING.md
它非常清楚地告诉了你如何撤消之前所做的修改。 让我们来按照提示执行:
$ git checkout -- CONTRIBUTING.md
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
renamed: README.md -> README
可以看到那些修改已经被撤消了。
git checkout <tagname> 回滚工作区到某个标签对应的版本
git checkout <tagname>
会使当前工作区进入“分离头指针(detached HEAD)”的状态,并将标签对应的版本替换到本地工作区中。
你可以浏览并修改代码文件,但若想要保存修改,必须新建一个分支并切换过去:
$ git checkout -b version2 v2.0.0
Switched to a new branch 'version2'
新建跟踪分支
在使用 git clone 或 git fetch 拉取某个远程仓库后,不能直接对远程仓库的分支进行修改,而是需要新建一个对应的副本分支,完成修改后与远程仓库分支合并。
当克隆一个仓库时,它通常会自动地创建一个跟踪 origin/master
的 master
分支。若想创建其他分支的跟踪分支,则可以使用运行 git checkout -b <branch> <remote>/<branch>
。 这是一个十分常用的操作所以 Git 提供了 --track
快捷方式:
$ git checkout --track origin/serverfix
Branch serverfix set up to track remote branch serverfix from origin.
Switched to a new branch 'serverfix'
效果是新建一个跟踪分支,对应远程仓库 origin 上的 serverfix 分支。
若尝试切换到的分支在本地不存在,而远程仓库中刚好有一个与之匹配的分支,则会自动进行创建其跟踪分支:
$ git checkout serverfix
Branch serverfix set up to track remote branch serverfix from origin.
Switched to a new branch 'serverfix'
若想重命名远程分支对应的追踪分支名称,可以使用标准的 git checkout
命令:
$ git checkout -b sf origin/serverfix
Branch sf set up to track remote branch serverfix from origin.
Switched to a new branch 'sf'
绑定已有的本地分支到某个上游分支
设置已有的本地分支跟踪一个刚刚拉取下来的远程分支,或者想要修改正在跟踪的上游分支, 你可以在任意时间使用 -u
或 --set-upstream-to
选项运行 git branch
来显式地设置。
$ git branch -u origin/serverfix
Branch serverfix set up to track remote branch serverfix from origin.
当设置好跟踪分支后,可以通过简写 @{upstream}
或 @{u}
来引用它的上游分支。 所以在 master
分支时并且它正在跟踪 origin/master
时,如果愿意的话可以使用 git merge @{u}
来取代 git merge origin/master
。