Normally, there's an ad running in this spot, but you're using an ad blocker. To help support our blog, which provides free tutorials for everybody, we just ask that you whitelist or follow us on facebook, twitter, or subscribe using the form to the leftabove. Thank you!

    Git Subtrees vs Git Submodules

    Subtree's Strengths Over Submodule

    • Older versions of git are supported.
    • Subtree is less intrusive to other collaborators on the repository. They can flat out ignore that the subtree exists.
    • Fewer modifications to your workflow. You'll have to learn about a new merge strategy (i.e.subtree), but this requires you to learn fewer steps and commands that come along with submodule.
    • Avoids the deployment issues that come with submodule when the submodule is private and hosted on a private server.

    One major drawback, however, is that you have to be careful not to mix the super and subtree code in your commits.

    What Exactly is Git Subtree?

    Subtree basically allows you nest one repository into a subdirectory or your main repo. And from within the main repo, you have the ability to merge the master or any branch of the subrepo into a specified subdirectory or number of subdirectories. Also, if you make any changes to the files that are tracked in the subtree, you can actually push those changes to the subrepo's upstream.

    Adding / Removing a Git Subtree

    To add a git subtree, perform the following steps.

    # add a remote to repo
    $ git remote add my-repo
    # add subtree
    # path/for/subtree is where the subtree content should live
    $ git subtree add --prefix=path/for/subtree my-repo branch
    # remove subtree
    $ git rm path/for/subtree

    Updating a Git Subtree

    To push and pull from the git subtree, perform the following steps:

    # push to subtree's repo
    $ git subtree push --prefix=path/to-repo my-repo branch
    # pull changes from subtree's repo back to main repo
    $ git subtree pull --prefix=path/to-repo my-repo branch

    Adding / Removing a Git Submodule

    To add a git submodule, navigate into your main repository, and perform the following steps.

    # add a submodule
    $ git submodule add git@myorganization:my-submodule lib/my-submodule
    $ cat .gitmodules
    [submodule "lib/my-submodule"]
    path = lib/my-submodule
    url = git@myorganization:my-submodule
    # initialize the submodule
    $ git submodule init
    $ git submodule update
    # removing submodules
    $ git submodule rm lib/my-submodule

    Updating a Git Submodule

    To update a git submodule, perform the following steps.

    # navigate into the submodule directory
    cd lib/my-submodule
    # updating a submodule
    $ git checkout master
    $ git pull

    Did you like this tutorial? Help us pay for server costs by following us on Facebook, Twitter, and subscribing below, where you'll get post notifications, training webinar invites, and free bundles.