For one branch, see the question phd linked-to, i.e., Make an existing Git branch track a remote branch?
To do this for some set of branches, use a loop. To do it for all branches, use git for-each-ref
to loop over all branches, as in this sh / bash looping construct:
git for-each-ref --format='%(refname:short)' |
while read name; do
git branch --set-upstream-to=origin/$name $name
done
(which is all one line, really, just broken into more readable lines here).
This assumes you want the upstream name for each name
to be origin/name
. If not, substitute appropriately. Note that this will override any existing upstream set for each such name, or fail if no upstream with that name exists yet.
If origin/xyzzy
does not exist yet, you cannot set branch xyzzy
to have origin/xyzzy
as its upstream. This is perfectly logical. However, it may not be what you want.
You can override Git's intelligence about this by going below the level of git branch
, replacing the git branch --set-upstream-to
with raw git config
operations:
git for-each-ref --format='%(refname:short)' |
while read name; do
git config branch.$name.remote origin
git config branch.$name.merge refs/heads/$name
done
This assumes that your remote.origin.fetch
setting is +refs/heads/*:refs/remotes/origin/*
. If it is not, you should already know what you are doing and how to modify the above loop.
Note that setting the upstream to a nonexistent remote-tracking name will make Git believe that the name used to exist and is now gone: git branch -vv
will report the upstream as "gone". Git is not very smart about causality, so it thinks that if the upstream is set to a nonexistent branch, the causal sequence must have been:
- upstream exists
- branch's upstream is set to existing upstream
- upstream is deleted, causing branch's upstream to be set inappropriately
when in fact the actual cause was that you set the upstream inappropriately on purpose, in anticipation of the setting becoming appropriate in the future. So ignore the "gone" annotation.