git:推送跟踪特定远程的所有本地分支

git: Push all local branches that track a specific remote

我正在寻找 git push --all 的等效项,它仅限于指定的 remote 并且仅推送跟踪 that 远程的本地分支。

git push --all myremote 并不能解决问题,例如:

% git push nh2github --all --dry-run
To github.com:nh2/myrepo.git
 + f4165c1e160...6882a13b8c1 branch1-tracking-nh2github -> branch1-tracking-nh2github
 + e5998342793...010aa57c786 branch2-tracking-nh2github -> branch2-tracking-nh2github
 * [new branch]              branch3-tracking-otherremote -> branch3-tracking-otherremote

这不好,因为它会推送 所有 本地分支,包括那些跟踪与我指定的 nh2github 不同的 remote 的分支。

如何做到这一点?

您可以从 git config -l 中 grep 到链接到特定远程的分支:

# each branch linked to a remote will have two lines :
#   branch.[branch name].remote = trackedremote
#   branch.[branch name].merge = refs/heads/remote/name
# you can keep the local branches that track a ref from targetremote :
git config -l | grep '^branch\.' | grep '\.remote = targetremote$'

# use another command to extract the actual branch name :
# awk would work
... | awk -F . '{ print  }'

然后您可以将分支列表提供给 git push :

branches=$(command above)
git push targetremote $branches

要列出分支机构及其上游分支机构,我推荐 git for-each-ref:

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

通过使用 awk(打印分支名称)选择的远程过滤列表:

git for-each-ref refs/heads --format='%(refname:short) %(upstream)' |
    awk ' ~ /^refs\/remotes\/<MYREMOTE>\// {print }'

现在开始推送:

git for-each-ref refs/heads --format='%(refname:short) %(upstream)' |
    awk ' ~ /^refs\/remotes\/<MYREMOTE>\// {print }' |
    xargs git push <MYREMOTE>

(在上面,将 <MYREMOTE> 替换为您的遥控器名称。)