如何在不将其添加到 master 的情况下将新文件夹添加到 git branch

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17890693/
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 08:50:11  来源:igfitidea点击:

How to add new folder to git branch without adding it to master

gitgit-branch

提问by binarygiant

How does one add a new folder to a branch in git without having that folder show up in the master branch?

如何将一个新文件夹添加到 git 中的一个分支而该文件夹不显示在 master 分支中?

e.g. 
git branch myNewBranch
git checkout myNewBranch
mkdir foo

git checkout master
ls

the myNewBranch directory is also added to master

myNewBranch 目录也被添加到 master

回答by Alex Ionescu

Just because you created the folder git will not automatically start version controlling it. The folder you created is unknown to git so git will not touch it.

仅仅因为您创建了文件夹 git 不会自动启动版本控制它。你创建的文件夹对 git 来说是未知的,所以 git 不会接触它。

git init #create repo
touch file1.txt
git add file1.txt
git commit -m 'initial commit'
git branch newBranch
git checkout newBranch
mkdir folder
touch folder/file2.txt
git add folder #tell git we want to track the folder
git commit -m 'second commit'
git checkout master
# folder/file2.txt is not available as expected.

Edit: To clarify the folder in your example was not added to master, it actually was not added to any branch.

编辑:为了澄清您的示例中的文件夹没有添加到 master,它实际上没有添加到任何分支。

回答by Peter Lundgren

It would seem you have 2 misconceptions that are confusing you.

您似乎有两个误解使您感到困惑。

  1. Git does not overwrite unstaged changes when you switch branches. You need to addand commita file before Git will do anything to that file (like modify or remove it when you checkout a different branch).
  2. Git does not track directories, it only tracks files. You cannot version an empty directory in Git. If you want to commit an empty directory to Git, the conventional workaround is to add an empty .gitignorein that directory and commit that.
  1. 当您切换分支时,Git 不会覆盖未暂存的更改。在 Git 对该文件执行任何操作之前,您需要addcommit一个文件(例如在您签出不同的分支时修改或删除它)。
  2. Git 不跟踪目录,它只跟踪文件。您不能在 Git 中对空目录进行版本控制。如果你想向 Git 提交一个空目录,传统的解决方法是.gitignore在该目录中添加一个空目录并提交。