如何在“git checkout”上更新工作目录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7902144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 06:06:11  来源:igfitidea点击:

How the working directory is updated on "git checkout"?

gitgit-branchgit-checkout

提问by Misha Moroshko

Consider the following "story":

考虑以下“故事”:

$ 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

Why hello.txthas two lines on branch master? (I thought that git checkoutwill revert the working directory to the previous state, i.e. hello.txtwill have only one line.)

为什么hello.txt在 branch master上有两条线?(我认为这git checkout会将工作目录恢复到以前的状态,即hello.txt只有一行。)

What actually happens behind the scenes to the working directory on git checkout? How it is updated?

实际工作目录在幕后发生了什么git checkout?它是如何更新的?

回答by scube

Your git checkout to master prevents you from losing uncommitted changes. Thats why you still have your second line in your hello.txtfile. If you really want to lose your uncommitted changes you have to use the -fparameter.

您对 master 的 git checkout 可防止您丢失未提交的更改。这就是为什么您的hello.txt文件中仍然有第二行的原因。如果您真的想丢失未提交的更改,则必须使用该-f参数。

Finally your checkout would look like this:

最后,您的结帐将如下所示:

git checkout -f master

回答by Noufal Ibrahim

Git checkout (loosely) will update the working copy with the contents of the repository at the commit which specify. Your new_featurebranch doesn't have the second line which you've added to your file (since you haven't committed it yet). Right now, that extra line is just an untracked change in your working copy and it will get added to the branch on which you commit it.

Git checkout(松散地)将在指定的提交时使用存储库的内容更新工作副本。您的new_feature分支没有您添加到文件中的第二行(因为您还没有提交)。现在,额外的行只是您工作副本中未跟踪的更改,它将被添加到您提交它的分支中。

回答by user2609605

Git will checkout as expected if adding second line had been committed to new_feature. Uncommitted changes normally prevent from checkout but here it is a merge.

如果添加第二行已提交给 new_feature,Git 将按预期结帐。未提交的更改通常会阻止结帐,但这里是合并。