7

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?

y2k-shubham
  • 10,183
  • 11
  • 55
  • 131
  • 1
    `git submodule update` would update them (to detached HEAD) anyway. How are you going to utilize the current branches? – max630 Dec 15 '17 at 16:54
  • **@max630** you are right. Its just that in my team we don't *normally* use `git submodule update`. Rather we do `git pull --rebase origin master --recurse-submodules`, so that each `submodule` gets `rebase`d with `master` (irrespective of which `branch` is currently *checked-out* in `submodule`s). I acknowledge that this serves my *isolated use-case* and may not be required by majority of people – y2k-shubham Mar 23 '18 at 07:30

2 Answers2

5

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]

Martin Schüller
  • 904
  • 1
  • 9
  • 7
4

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.

y2k-shubham
  • 10,183
  • 11
  • 55
  • 131