Detach (Move) Subdirectory into Separate Git Repository
To detach (move) a subdirectory into a separate Git repository, you can use the git subtree
command. This approach allows you to preserve the history of the subdirectory. Here are the steps to achieve this:
Navigate to your repository:
cd path/to/your/repository
Split the subdirectory into a separate branch:
Use the
git subtree split
command to create a new branch that contains the history of the subdirectory. Replacesubdir
with the path to your subdirectory.git subtree split --prefix=subdir -b subdir-branch
Create a new repository:
Initialize a new Git repository for the subdirectory.
mkdir path/to/new/repository cd path/to/new/repository git init
Pull the subdirectory branch into the new repository:
Use the
git pull
command to pull the newly created branch from the old repository into the new repository. Adjust the path to your old repository accordingly.git pull path/to/your/old/repository subdir-branch
Optional: Remove the subdirectory from the original repository:
If you want to remove the subdirectory from the original repository, you can do so and commit the changes.
cd path/to/your/repository git rm -r subdir git commit -m "Remove subdir after extracting it to a new repository"
Example
Assuming you have a repository with the following structure:
/your-repository
/subdir
/otherdir
And you want to move /subdir
to a new repository:
Navigate to your original repository:
cd path/to/your-repository
Split the subdirectory into a separate branch:
git subtree split --prefix=subdir -b subdir-branch
Create a new repository for the subdirectory:
mkdir ../new-subdir-repo cd ../new-subdir-repo git init
Pull the subdirectory branch into the new repository:
git pull ../your-repository subdir-branch
Remove the subdirectory from the original repository (optional):
cd ../your-repository git rm -r subdir git commit -m "Remove subdir after extracting it to a new repository"
Notes
- The
git subtree
method preserves the commit history of the subdirectory. - Ensure you have the correct paths and branch names when running the commands.
- If you need to push the new repository to a remote server, you can follow up with
git remote add origin <url>
andgit push -u origin master
.
By following these steps, you will have successfully moved a subdirectory into a separate Git repository while retaining its history.
Make your mark
Join the writer's program
Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.
Write for usBuild on top of Better Stack
Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.
community@betterstack.comor submit a pull request and help us build better products for everyone.
See the full list of amazing projects on github