Search code examples
gitgit-pushmultiple-repositories

How to push a branch only if it differs from master?


The goal

I would like to push a branch only if it differs from the local master. More specifically, I don't want to push a branch if it points to the same commit as the local master.

Background

My company has hundreds of git repositories, and we don't use git submodules, so for system-wide cleanups I have a very simple bash script:

for gitdir in `find ./ -name .git|sort`;
    do 
        workdir=${gitdir%/*}; 
        cd $workdir
        eval "$*"
        cd $BASE_DIR
    done

that I run like this:

./for_each_repo.sh 'git checkout -b <bname> && <some command> && git commit -m <message>''

Then I may do some other changes to the repositories.

Finally, I run:

./for_each_repo.sh 'git push origin <bname>'

But his, obviously..., pushes also "empty" branches (i.e. where I just created a branch but did not commit to it).


Solution

  • First,

    git for-each-ref --no-merged=master --format='%(refname:short)' refs/heads
    

    would list all branches with new commits (which aren't yet merged into master).

    Then, you could link that to your push command

    git push origin $(git for-each-ref --no-merged=master --format='%(refname:short)' refs/heads)