考虑以下“故事”:
$ mkdir my_project
$ cd my_project
$ git init
Initialized empty Git repository in /home/misha/misha/my_project/.git/
$ echo "first line" > hello.txt
$ git add hello.txt
$ git commit -m "first commit"
[master (root-commit) 9c913a1] first commit
1 files changed, 1 insertions(+), 0 deletions(-)
create mode 100644 hello.txt
$ git branch new_feature
$ git checkout new_feature
Switched to branch 'new_feature'
$ echo "second line" >> hello.txt
$ cat hello.txt
first line
second line
$ git checkout master
M hello.txt
Switched to branch 'master'
$ cat hello.txt
first line
second line
为什么hello.txt
在分支master上有两行? (我以为git checkout
会将工作目录还原到以前的状态,即hello.txt
只有一行。)
幕后到git checkout
上的工作目录实际上发生了什么?如何更新?
您的git checkout可以防止您丢失未提交的更改。这就是为什么您在hello.txt
文件中仍然保留第二行的原因。如果您确实要丢失未提交的更改,则必须使用-f
参数。
最后,您的结帐如下所示:
git checkout -f master
Git签出(松散地)将在指定的提交时使用存储库的内容更新工作副本。您的new_feature
分支没有添加到文件的第二行(因为尚未提交)。现在,该额外的行只是您的工作副本中的未跟踪更改,它将被添加到您提交它的分支中。
如果已将第二行添加到new_feature中,Git将按预期方式签出。未提交的更改通常会阻止检出,但此处是合并。