【问题标题】:Why git keeps showing my changes when I switch branches (modified,added, deleted files) no matter if I run git add or not?为什么无论我是否运行 git add,当我切换分支(修改、添加、删除的文件)时,git 都会显示我的更改?
【发布时间】:2011-04-03 17:55:02
【问题描述】:

我真的是 git 的新手,我一直试图理解为什么当我运行 git checkout 以在分支之间切换时,git 总是显示我在另一个分支的一个分支中所做的任何更改首先我尝试不使用 git add 并且没有不工作。但是,我尝试使用 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”以避免这种情况?

【问题讨论】:

    标签: git


    【解决方案1】:

    切换分支会随身携带未提交的更改。要么先提交,要么运行git checkout . 撤消它们,或者在切换之前运行git stash。 (您可以通过git stash apply 取回您的更改)

    【讨论】:

    • git stash pop 更好,除非你想建立一个巨大的存储堆栈。
    • @JPZ: git stash 只处理被跟踪的文件;新文件不会被跟踪,因此它们不会被隐藏。
    • @JPZ:如果您想隐藏未跟踪的文件,可以在隐藏之前git add它们。也就是说,我不确定您是否真的想要存储在这里 - 如果您打算让这些更改成为您要切换的分支的一部分,请提交它们。 (如果您打算切换回该分支并在提交更改之前进一步处理更改,那么stash 可能是适合该工作的工具。)
    • “切换分支会随身携带未提交的更改”——这确实有道理,也许是最糟糕的设计理念。如果您不能以孤立的方式工作,那么拥有分支机构有什么意义? !!!
    • 就我而言,我有一个来自开发分支的功能分支。我在功能分支中提交,但是当我签出开发分支时它也会显示更改。
    【解决方案2】:

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

    分支是指向提交的指针。当您在签出分支的情况下提交时,该分支会前进以指向该新提交。当您签出一个分支时,您正在签出它指向的提交。 (您可以将提交视为工作树的快照。)

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

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

    【讨论】:

      猜你喜欢
      • 2016-12-17
      • 2016-12-18
      • 2023-03-20
      • 1970-01-01
      • 2019-08-01
      • 2011-08-18
      • 2011-10-02
      • 2018-12-17
      • 1970-01-01
      相关资源
      最近更新 更多