y2k-shubham
y2k-shubham

Reputation: 11607

Git: Recursively switching branch (checkout) on all submodules

I'm working on a git repo that contains submodules. I've got branches by the same name (like master, development..) in all submodules (including parent module) and they all track their corresponding remote branches.

I'd like to have same branches checked-out in all submodules at a time. In other words, what I want is that if I switch to development branch in parent module, all submodules should also switch to development branch so that my working tree remains consistent with branches.

Manually doing this is painful and repetitive. Is there is shortcut?

Upvotes: 7

Views: 13477

Answers (2)

Martin Schüller
Martin Schüller

Reputation: 1034

You can use the --recurse-submodule flag. E.g.: git checkout master --recurse-submodules

Using --recurse-submodules will update the content of all initialized submodules according to the commit recorded in the superproject. [https://git-scm.com/docs/git-checkout#git-checkout---no-recurse-submodules]

Upvotes: 9

y2k-shubham
y2k-shubham

Reputation: 11607

I achieved this with the help of git-alias and a bash script.

Following is my bash script called git-rcheckout.sh taken from @qbein's answer

#!/bin/bash
((!$#)) && echo No branch name, command ignored! && exit 1
git checkout $1 && git submodule foreach --recursive git checkout $1

Next I aliased this script to rcheckout command as told by @u0b34a0f6ae

git config --global alias.rcheckout '!sh ~/path/to/script/git-rcheckout.sh'

ISSUE: Currently it works only when you do git rcheckout branch-name from parent module. You can probably update the bash script to do it from submodules also, but I'm too lazy. So suggestions are welcomed.

Upvotes: 6

Related Questions