我们正在使用git存储库来存储我们的项目。我们的分支脱离了原来的分支。但是现在我们想要创建一个小的新项目来跟踪一些文档。为此,我们需要创建一个新的空分支来开始存储我们的文件,并且我希望网络上的其他用户克隆该分支。

我们怎么做呢?

我试过一些方法,但都没用。

$ mkdir proj_doc; cd proj_doc
$ git init
$ git add .
$ git commit -m 'first commit'
$ git br proj_doc
$ git co proj_doc
$ git br -d master
$ git push origin proj_doc

它似乎推了分支,但当我进行取回或拉取时,它从其他分支下载信息,然后我也从其他项目获得一些额外的文件。最好的解决办法是什么?


当前回答

如果你的git版本没有——orphan选项,应该使用这个方法:

git symbolic-ref HEAD refs/heads/<newbranch> 
rm .git/index 
git clean -fdx 

在做了一些工作之后:

git add -A
git commit -m <message>
git push origin <newbranch>

其他回答

如果你的git版本没有——orphan选项,应该使用这个方法:

git symbolic-ref HEAD refs/heads/<newbranch> 
rm .git/index 
git clean -fdx 

在做了一些工作之后:

git add -A
git commit -m <message>
git push origin <newbranch>

我发现这个方法很有用:

git checkout --orphan empty.branch.name
git rm --cached -r .
echo "init empty branch" > README.md
git add README.md
git commit -m "init empty branch"

你可以创建一个孤儿分支:

git checkout --orphan <branchname>

这将创建一个没有父结点的新分支。然后,您可以使用以下命令清除工作目录:

git rm --cached -r .

添加文档文件,提交到github上。

pull或fetch总是会更新关于所有远程分支的本地信息。如果您只想为单个远程分支提取/获取信息,则需要指定它。

2022年更新

从Git 2.23开始,你可以使用Git switch——orphan <new branch>来创建一个没有历史记录的空分支。不像git签出——孤儿,所有跟踪文件将被删除。

一旦你真的在这个分支上提交了,它就可以被推送到远程存储库:

git switch --orphan <new branch>
git commit --allow-empty -m "Initial commit on orphan branch"
git push -u origin <new branch>

正确的答案是创建一个孤儿分支。我在我的博客上详细解释了如何做到这一点。(归档链接)

... Before starting, upgrade to the latest version of GIT. To make sure you’re running the latest version, run which git If it spits out an old version, you may need to augment your PATH with the folder containing the version you just installed. Ok, we’re ready. After doing a cd into the folder containing your git checkout, create an orphan branch. For this example, I’ll name the branch “mybranch”. git checkout --orphan mybranch Delete everything in the orphan branch git rm -rf . Make some changes vi README.txt Add and commit the changes git add README.txt git commit -m "Adding readme file" That’s it. If you run git log you’ll notice that the commit history starts from scratch. To switch back to your master branch, just run git checkout master You can return to the orphan branch by running git checkout mybranch