Working with a Git repository, you may be required to move a specific directory to a new repository. If you just copy the directory content from one repository to another repository, you will lose the commit history. So follow this tutorial to remove a directory to a new Git repository with preserving the commit history.
In this tutorial, you will learn to move a directory from a Git repository to a new Git repository.
Move Directory to a New Git Repository
Follow the below steps to move a folder from an existing repository to a new repository.
- First of all, clone the main repository that contains a directory to move.
git clone https://github.com/USERNAME/PRIMARY-REPO.git
- Change directory to the newly cloned repository
cd REPOSITORY-NAME
- Next, the filter-branch option lets you rewrite Git revision history by rewriting the branches mentioned in the command line. This will filter the subdirectory from the rest of the files in the current repository.
git filter-branch --prune-empty --subdirectory-filter SUB_DIRECTORY_NAME BRANCH_NAME
Here:
- SUB_DIRECTORY_NAME: The relative path to the directory within the project files, you need to separate from others.
- BRANCH_NAME: Select the branch name from which the directory will be filtered, like “main”, “master”, “develop” etc.
Once the above command executed successfully, you will see that the current directory has only files that were in the subdirectory.
- Create a new repository on GitHub, Gitlab, or any other Git providers.
- Set the new URL as the origin of the current directory. This is the same directory where you have filtered code from the previous git repository.
git remote set-url origin https://github.com/USERNAME/NEW_REPO_NAME.git
- Next, verify that the Git origin URLs have been updated in the current directory.
git remote -v
You will see the following output:
# Verify new remote URL > origin https://github.com/USERNAME/NEW_REPO_NAME.git (fetch) > origin https://github.com/USERNAME/NEW_REPO_NAME.git (push)
- Finally, Push all the files to the new repository.
git push -u origin BRANCH_NAME
Congratulations, You have successfully copied a directory to a new Git repository.