我们正在使用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 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 branch  
master
> ls -la # (files and dirs which you may keep in master)
.git
directory1
directory2
file_1
..
file_n

如何一步一步地创建一个空分支:

Git checkout -orphan new_branch_name 执行以下命令前请确认所在目录正确。 ls -la |awk '{print $9}' |grep -v git |xargs -I _ rm -rf ./_ Git rm -rf。 触摸new_file Git添加了new_file Git commit -m '在新分支中添加第一个文件' Git push origin new_branch_name

在步骤2中,我们简单地在本地删除所有文件,以避免与新分支上的文件和保留在主分支中的文件混淆。 然后,我们在步骤3中解除所有这些文件的链接。最后,第4步和之后将使用新的空分支。

一旦你完成了,你可以很容易地在你的分支之间切换:

git checkout master 
git checkout new_branch

创建一个空的新分支,像这样:

true | git mktree | xargs git commit-tree | xargs git branch proj-doc

如果你的proji -doc文件已经在一个单独的子目录下提交,你可以这样创建新的分支:

git commit-tree thatcommit:path/to/dir | xargs git branch proj-doc

这可能比git分支——orphan更方便,如果它会让你有很多git rm和git移动要做的话。

Try

git branch --set-upstream proj-doc origin/proj-doc

看看这能不能帮你解决"多拿"的问题。另外,如果你真的只想获取一个分支,在命令行上指定它是最安全的。

基于Hiery Nomus的回答。

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

git checkout --orphan <branchname>

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

git rm --cached -r .

然后你只需要用空commit和push来提交分支

git commit -m <commit message> --allow-empty
git push origin <newbranch>

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

git checkout --orphan <branchname>

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

git rm --cached -r .

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

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

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

... 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