How to Add and Remove Git Submodules
Projects sometimes need external modules. This article explains how to use Git submodules in that situation.
Overview
When you need to reference an external module, you can add or clone it with git submodule. Unlike git clone, git submodule can add multiple modules inside the same working directory.
This example adds the Hugo book theme as a submodule and then removes it.
Adding a Git submodule
Use git submodule add to add or clone an external module into the current working directory.
git submodule add {Git Repository URL} {Submodule Project directory}
% git submodule add https://github.com/alex-shpak/hugo-book.git themes/book
Cloning into '/Users/user/develop/devkuma-hugo-blog/themes/book'...
remote: Enumerating objects: 4124, done.
remote: Counting objects: 100% (6/6), done.
remote: Compressing objects: 100% (5/5), done.
remote: Total 4124 (delta 2), reused 2 (delta 1), pack-reused 4118
Receiving objects: 100% (4124/4124), 6.63 MiB | 5.50 MiB/s, done.
Resolving deltas: 100% (2122/2122), done.
Check the added files with git status.
% git status
On branch main
Your branch is up to date with 'origin/main'.
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
modified: .gitmodules
new file: themes/book
... omitted ...
Commit the changes with git commit.
git commit -m "{commit message}
Checking added submodules
If a submodule has been added, you can view the list of added modules with git submodule status.
% git submodule status
036e037a63ba06ca366adb1a0c3a005d1a0b15b8 themes/book (v9-54-g036e037)
Removing a Git submodule
First, remove the submodule with git submodule deinit.
git submodule deinit -f {Submodule Project directory}
% git submodule deinit -f themes/book
Cleared directory 'themes/book'
Submodule 'themes/book' (https://github.com/alex-shpak/hugo-book) unregistered for path 'themes/book'
Next, remove the corresponding directory under .git/modules with rm.
rm -rf .git/modules/{Submodule Project directory}
% rm -rf .git/modules/themes/book
Then remove the directory from Git.
git rm -f {Submodule Project directory}
% git rm -f themes/book
rm 'themes/book'
Finally, commit the removal of the external module.
git commit -m "{commit message}
% git commit -m "rm themes/book"
[main f9aaff69] rm themes/book
2 files changed, 4 deletions(-)
delete mode 160000 themes/book