Sometimes there would be a submodule or some submodules within one git repository, in some cases the submodule may be out of sync with the checkout state as some files in submodule may be changed unexpectedly. How to reset the submodule to be the same as the original checkout state?
Let's take an example that we have a git repository A and there is a submodule called ruby-gems under it. Assuming the submodule at remote origin has commit a.
And on our local environment, the repository A has a latest commit of the submodule which causes some diff difference.
$ git diff
diff --git a/web-api/ruby-gems b/web-api/ruby-gems
index 0359dc84d..8a711275a 160000
--- a/web-api/ruby-gems
+++ b/web-api/ruby-gems
@@ -1 +1 @@
-Subproject commit 0359dc84d22adf0e131165b72b3209318605dfe3
+Subproject commit 8a711275a4c34bd8cc22b07894931fa1743c5707
Now we want to reset the repository A's submodule commit back to 0359dc84d22adf0e131165b72b3209318605dfe3
so that there is no diff between local and remote repository.
$ git status
On branch master
Your branch is up to date with 'origin/master'.
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: web-api/ruby-gems (new commits)
no changes added to commit (use "git add" and/or "git commit -a")
It may not work if we just run git reset --hard
, in this case, we can run the git submodule
command to reset the submodule to its checkout state.
$ git submodule update --init
Submodule path 'web-api/ruby-gems': checked out '0359dc84d22adf0e131165b72b3209318605dfe3'
From above output, the submodule state is brought back to its checkout state. Can verify it with below command after above.
$ git status
On branch master
Your branch is up to date with 'origin/master'.
nothing to commit, working tree clean
If there are multiple submodules and want to reset all submodules state to checkout state, can run below command.
git submodule foreach --recursive git submodule update --init
Happy coding.