3

I would like to run a submodule update from outside my git project. For most commands (e.g. git status), I can give git --git-dir and --work-tree arguments, like so:

git --git-dir=/path/to/root/.git --work-tree=/path/to/root status

However, running git --git-dir=/path/to/root/.git --work-tree=/path/to/root submodule update gives the result: fatal: $program_name cannot be used without a working tree.

I am aware that I can change into the /path/to/root directory, however I would like to know if git has the ability to update submodules from outside of the git project.

Zambezi
  • 767
  • 1
  • 9
  • 19

2 Answers2

2

I was able to run a git command from within the submodule outside the main repository by doing git --git-dir=<path-to-repo>\.git\modules\<submodule-name>

This is because a submodules git directory is located at .git\modules\<submodule-name> folder, not inside the submodule itself (UNLESS you created your submodule on top of an exsiting repository in the first place, in which case you can run git submodule absorbgitdirs to fix this). Note that from a fresh clone, the .git\modules\<submodule-name> folder will not exist until you run git submodule update for the first time.

However, I hit the same problem as you when trying to run git submodule update using a --git-dir of the main repository. It did not work both with and without specifying a work tree. I wonder if this is a bug, or we are doing something wrong.

However, because the first command I linked worked, you can just do the following:

git --git-dir=<path-to-repo>\.git\modules\<submodule-name> pull

Which will run git pull in your submodule from outside the main repository.

Forrest Coward
  • 113
  • 1
  • 6
2

My use case is init/updating a submodule within a Lerna/yarn workspaces repo.

The answer is here: https://stackoverflow.com/a/35899275

Combined with looking at git docs for the -C flag and git docs for using submodules, I arrived at:

git -C ./dir/to/submodule submodule update --init

The main thing to note from git docs, in contrast to using --git-dir or --work-tree, the -C flag "Run[s] as if git was started in <path> instead of the current working directory."

I then added as a script to my package.json to make updating easier and for contributors to get started.

Update The above command only works to init. I found I had to run this command to actually "update" the submodule to latest:

git -C ./dir/to/submodule pull <remote> <branch>

Note: the alternative to the above init command is add the --recurse-submodules flag when first cloning a repo:

git clone --recurse-submodules <git-url>
bearcanrun
  • 46
  • 3