簡體   English   中英

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

[英]How the working directory is updated on "git checkout"?

考慮以下“故事”:

$ 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.txtmaster分支上有兩行? (我以為git checkout會將工作目錄恢復到以前的狀態,即hello.txt將只有一行。)

git checkout上的工作目錄在幕后實際發生了什么? 它是如何更新的?

您對 master 的 git checkout 可防止您丟失未提交的更改。 這就是為什么你的hello.txt文件中還有第二行。 如果您真的想丟失未提交的更改,則必須使用-f參數。

最后,您的結帳將如下所示:

git checkout -f master

Git checkout(松散地)將在指定的提交時使用存儲庫的內容更新工作副本。 您的new_feature分支沒有您添加到文件中的第二行(因為您還沒有提交)。 現在,那條額外的行只是您工作副本中未跟蹤的更改,它將被添加到您提交它的分支中。

如果添加第二行已提交給 new_feature,Git 將按預期結帳。 未提交的更改通常會阻止結帳,但這里是合並。

Git checkout 不會替換文件系統中的文件。 Git checkout 會更改您所在的分支。 更改分支不會更改文件系統上的內容。 我喜歡認為這棵樹看起來像這樣:

  1. 遠程倉庫
    1.a. 掌握
    1.b. 特征
  2. 本地回購
    2.a. 掌握
    2.b. 特征
  3. 未提交的代碼/文件系統

結帳 -> 在 a 和 b 之間切換

Pull -> 將當前分支中新的未同步的東西從 1 復制到 2

推送 -> 從當前分支中的新內容從 2 復制到 1

提交 -> 將新東西從 3 復制到 2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM