# 将子文件夹拆分为新存储库

您可以将 Git 仓库内的文件夹变为全新的仓库。

> \[!NOTE]
> 需要 Git 版本 2.22.0 或更高版本才能按照这些说明进行操作，否则 `git filter-repo` 将不起作用。

如果您创建仓库的新克隆副本，则将文件夹拆分为单独的仓库时不会丢失任何 Git 历史记录或更改。 但是，请注意，新存储库不会具有原始存储库的分支和标记。

1. 打开<span class="platform-mac">终端</span><span class="platform-linux">终端</span><span class="platform-windows">Git Bash</span>。

2. 将当前工作目录切换到您要创建新仓库的目录位置。

3. 克隆包含该子文件夹的仓库。

   ```shell
   git clone https://github.com/USERNAME/REPOSITORY-NAME
   ```

4. 将当前工作目录切换到克隆的存储库。

   ```shell
   cd REPOSITORY-NAME
   ```

5. 若要从存储库中的其余文件中筛选出子文件夹，请安装 [`git-filter-repo`](https://github.com/newren/git-filter-repo)，然后使用以下参数运行 `git filter-repo`。

   * `FOLDER-NAME`：项目中要在其中创建单独存储库的文件夹。

   <div class="ghd-tool windows">

   > \[!TIP]
   > Windows用户应使用 `/` 分隔文件夹。

   </div>

   ```shell
   $ git filter-repo --path FOLDER-NAME/
   # Filter the specified branch in your directory and remove empty commits
   ```

   现在，该仓库应仅包含您的子文件夹中的文件。

   如果希望将某个特定子文件夹用作新存储库的新根文件夹，可使用以下命令：

   ```shell
   $ git filter-repo --subdirectory-filter FOLDER-NAME
   # Filter the specific branch by using a single sub-directory as the root for the new repository
   ```

6. 在 GitHub 上[创建新存储库](/zh/repositories/creating-and-managing-repositories/creating-a-new-repository)。

7. 在 GitHub 的快速设置页面上的新存储库顶部，单击 <svg version="1.1" width="16" height="16" viewBox="0 0 16 16" class="octicon octicon-copy" aria-label="Copy to clipboard" role="img"><path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25Z"></path><path d="M5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25Zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Z"></path></svg> 以复制远程存储库 URL。

   ![存储库中“快速设置”标头的屏幕截图。 在远程 URL 旁边，两个正方形相重叠的图标以橙色框出。](/assets/images/help/repository/copy-remote-repository-url-quick-setup.png)

   > \[!TIP]
   > 有关 HTTPS 和 SSH URL 之间区别的信息，请参阅 [关于远程仓库](/zh/get-started/git-basics/about-remote-repositories)。

8. 使用您为仓库复制的 URL 来新增远程名称。 例如，`origin` 或 `upstream` 是两个常见的选项。

   ```shell
   git remote add origin https://github.com/USERNAME/REPOSITORY-NAME.git
   ```

9. 用新的存储库名称验证是否已添加远程 URL。

   ```shell
   $ git remote -v
   # Verify new remote URL
   > origin  https://github.com/USERNAME/NEW-REPOSITORY-NAME.git (fetch)
   > origin  https://github.com/USERNAME/NEW-REPOSITORY-NAME.git (push)
   ```

10. 将更改推送到 GitHub 上的新存储库。

    ```shell
    git push -u origin BRANCH-NAME
    ```