为什么无论我是否运行git add,当我切换分支(修改,添加,删除的文件)时git仍然显示更改?


115

我对git真的很陌生,我一直在尝试理解为什么git为什么在我运行git checkout来在两个分支之间切换时,在另一个分支的一个分支中不断显示更改的内容。但是,我尝试然后使用git add,但没有解决问题。我还没有使用git commit。

这基本上就是我在做什么:

$ git clone <a_repository>  
$ git branch  
* master  
$ git branch testing  
$ git checkout testing  
...edit a file, add a new one, delete...  
$ git status  
    # On branch testing  
    # Changed but not updated:  
    #   (use "git add/rm <file>..." to update what will be committed)  
    #   (use "git checkout -- <file>..." to discard changes in working directory)  
    #  
    #       deleted:    file1.txt  
    #  
    # Untracked files:  
    #   (use "git add <file>..." to include in what will be committed)  
    #  
    #       file2.txt  
no changes added to commit (use "git add" and/or "git commit -a")  
$ git branch  
  master  
* testing  
$ git checkout master  
D       file1.txt  
Switched to branch 'master'  
$ git status  
    # On branch master  
    # Changed but not updated:  
    #   (use "git add/rm <file>..." to update what will be committed)  
    #   (use "git checkout -- <file>..." to discard changes in working directory)  
    #  
    #       deleted:    file1.txt  
    #  
    # Untracked files:  
    #   (use "git add <file>..." to include in what will be committed)  
    #  
    #       file2.txt  
no changes added to commit (use "git add" and/or "git commit -a")  

我认为,在使用分支时,无论您在一个分支中做什么,其他所有分支都不可见。这不是创建分支的原因吗?

我尝试使用“ git add”,但更改在两个分支中均可见。我需要在分支之间切换之前运行“ git commit”以避免这种情况吗?

Answers:


142

切换分支机构会带来未提交的更改。要么先提交,要么git checkout .撤消它们,要么先运行git stash再切换。(您可以使用来找回更改git stash apply


10
git stash pop更好,除非您想建立大量的存储。
siride 2011年

7
@JPZ:git stash仅处理跟踪的文件;不会跟踪新文件,因此不会藏起来。
siride 2011年

2
@JPZ:如果您想隐藏未跟踪的文件,则要做的是git add在存储它们之前。就是说,我不确定您是否真的想将其存储在这里-如果您打算将那些更改作为要转离的分支的一部分,请提交它们。(如果您打算切换回该分支并在提交更改之前进行更多更改,那么stash可能是完成此工作的正确工具。)
Cascabel 2011年

16
“切换分支会带来未完成的更改” –这确实是合理的,而且可能是最糟糕的设计思想。如果您不能以孤立的方式工作,那么拥有分支有什么意义呢?!!!
nehem

1
就我而言,我有一个来自开发分支的功能分支。我提交了功能分支,但是当我结帐开发分支时,它也显示了更改。
Hitesh Garg'7

31

简短的回答:是的,您需要提交。不过,请确保在正确的分支上执行此操作!

分支是指向提交的指针。当您提交带有分支的签出时,分支前进以指向该新提交。签出分支时,即签出它指向的提交。(您可以将提交视为工作树的快照。)

因此,如果您有尚未提交的更改,它们将不会受到切换分支的影响。当然,如果切换分支与您的更改不兼容,git checkout则只会拒绝这样做。

git add是用于暂存更改的命令,您将随后提交。它不会将这些更改记录到存储库的历史记录中。它只是将它们放置在暂存区域(索引)中。git commit然后使用该暂存区的内容来创建提交。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.