Brian D
Brian D

Reputation: 10163

Changing an existing submodule's branch

When I initially added my submodule, I specified a particular branch, as seen in the .gitmodule file:

[submodule "externals/grpc/grpc"]
    path = externals/grpc/grpc
    url = git@github.com:me/grpc.git
    branch = release-1.0

I want to change to the master branch of my submodule, so I changed the branch in .gitmodules from release-1.0 to master, and for good measure, just deleted the submodule from my parent git tree:

cd $submodules
rm -rf grpc
cd $gitroot
git submodule sync
git submodule update --init --recursive

Now, when I go back to my submodule, it's still checked out from a commit on the release-1.0 branch, not the latest master commit.

What steps am I missing to switch my submodule's branch?

Upvotes: 74

Views: 142887

Answers (4)

http8086
http8086

Reputation: 1736

Since v2.22(Q3 2019) (thanks to @VonC in comments)

Suppose you have submodule xyz, the .gitmodules looks like

$ cat .gitmodules
[submodule "xyz"]
        path = xyz
        url = git@git.com:xyz.git
        branch = main

And you can check it with

$ git config --file=.gitmodules -l
submodule.xyz.path=xyz
submodule.xyz.url=git@git.com:xyz.git
submodule.xyz.branch=main

Now you want to ref branch v1.0.0 for xyz, you can run

git submodule set-branch -b v1.0.0 xyz

Then to sync the conf

git submodule sync

To update content for submodule xyz

git submodule update --init --remote xyz

To update ALL submodules regardless of local changes

git submodule update --init --recursive --remote

Upvotes: 56

SergO
SergO

Reputation: 2839

If you want to switch to a branch you've never tracked before.

After you have changed the branch in .gitmodules, do the following:

git submodule update --init --recursive --remote
cd submodule_name
git checkout new_branch_name

Upvotes: 36

user3804598
user3804598

Reputation: 425

The answer above (@milgner) didn't work me (git version 2.17.0). Maybe I did something wrong.

The below is what worked for me:

nano .gitmodules # substitute the needed branch here
git submodule update submodule_name # update the submodule
git add .gitmodules && git commit -m 'some comment' # add and commit
git submodule status # check that changes have been applied

Upvotes: 8

Marcus Ilgner
Marcus Ilgner

Reputation: 7241

Go into the directory where the submodule resides and git checkout the correct branch/commit. Then go up one level and git add and git commit the directory. This will check in the submodule with the correct commit.

And don't forget to run git submodule update --recursive on the other clients after updating them.

Upvotes: 73

Related Questions