home

git push to multiple remotes at once

2024-10-26

This entire blog is on a VPS with git push being the way to update it. It is a git repo configured with receive.denyCurrentBranch=updateInstead, and has been working “well” with my workflow.

However, I also “back up” this blog to a private repo on GitHub, and that is not something I remember to do every time.

A very basic approach could be configuring a second remote (which I already have) and configuring some alias to push to both remotes at once.

git remote add github git@github.com:thewisenerd/inanity.git
git config alias.pushall '!git push origin master && git push github master'

This still has the obvious problem of me remembering to use git pushall instead of git push. Searching around, I found this Stackoverflow answer which suggests that git supports this out of the box.

# configure the "primary" remote
> git remote add github git@github.com:thewisenerd/inanity.git
> git pull --set-upstream github master

# check remotes
> git remote -v
github  git@github.com:thewisenerd/inanity.git (fetch)
github  git@github.com:thewisenerd/inanity.git (push)

# however, if you check config, you will only find one remote
> git config -l | grep remote.github
remote.github.url=git@github.com:thewisenerd/inanity.git
remote.github.fetch=+refs/heads/*:refs/remotes/github/*

# why does this happen?
# because by default, the same URL gets used for both fetch and push.
# so, we first need to add the same URL once, to specifically set a push URL.
> git remote set-url --add --push github git@github.com:thewisenerd/inanity.git

# nothing "visibly" changed?
> git remote -v
github  git@github.com:thewisenerd/inanity.git (fetch)
github  git@github.com:thewisenerd/inanity.git (push)

# but, if you check the config again, you will find that remote.$name.pushurl has been added
> git config -l | grep remote.github
remote.github.url=git@github.com:thewisenerd/inanity.git
remote.github.fetch=+refs/heads/*:refs/remotes/github/*
remote.github.pushurl=git@github.com:thewisenerd/inanity.git

# now, we can add the second push URL
> git remote set-url --add --push github vps-host:directory/to/inanity

> git remote -v
github  git@github.com:thewisenerd/inanity.git (fetch)
github  git@github.com:thewisenerd/inanity.git (push)
github  vps-host:directory/to/inanity (push)

> git config -l | grep remote.github
remote.github.url=git@github.com:thewisenerd/inanity.git
remote.github.fetch=+refs/heads/*:refs/remotes/github/*
remote.github.pushurl=git@github.com:thewisenerd/inanity.git
remote.github.pushurl=vps-host:directory/to/inanity

# git push now pushes to both repos
> git push
Everything up-to-date
Everything up-to-date

# :)

home