The 'git submodule' Command
Learn about the "git submodule" command with the help of an example.
We'll cover the following
Git submodules solve these external repository dependency issues with a little overhead. Now that you understand local and remote repositories, it will be much easier to grasp how submodules work.
Tracking copies#
Git submodule commands are Git commands used to track copies of other repositories within your repository. The tracking is under your control (so you decide when it gets updated, regardless of how the other repository moves on), and the tracking is done within a file that is stored with your Git repository.
Pay Attention Here!
Git submodules can be very confusing if you don’t follow a few basic patterns or understand how they work. So it’s worth paying attention to this.
Let’s make this more clear with a walkthrough.
You are going to assume you have the alicelib
repository created in the previous lesson.
Create Bob’s repository (bob_repo
):
1 cd ..
2 mkdir bob_repo
3 cd bob_repo
4 git init
5 echo 'source alicelib' > file1
6 git add file1
7 git commit -am 'sourcing alicelib'
8 echo 'do something with alicelib 9 experimental' >> file1
10 git commit -am 'using alicelib experimental'
11 cat file1
Now you have Alice’s repository referenced in bob_repo
’s code, but bob_repo
does not have a link to alice_repo
’s code.
The first step to including alicelib
in bob_repo
is to initialize submodules:
12 git submodule init
Once a git submodule init
has been performed, you can git submodule add
the submodule you want:
13 git submodule add ../alicelib
A new file has been created (.gitmodules
), and the folder alicelib
has been created:
14 ls -a
alicelib
has been cloned just as any other Git repository would be anywhere else:
15 ls -a alicelib/
But the .gitmodules
file tracks where the submodule comes from:
16 cat .gitmodules
If you get confused, Git provides a useful git submodule status
command that works in a similar way to the standard git status
command:
17 git submodule status
Possible questions#
You may have some questions at this point such as:
- How do you get to the experimental branch?
- What happens if Alice’s branch changes? Does my code automatically update?
- What if I make a change to
alicelib
within my repository submodule checkout? Can I push those to Alice’s? Can I keep those private to my repository? - What if there are conflicts between these repositories?
And so on. I certainly had these questions when it came to Git submodules. With some trial and error, it took me some time to understand what was going on. I really recommend playing with these simple examples to get the relationships clear in your mind.