×

在一个命令中 同时推送到多个远程仓库

Falcon 2025-05-11 views:
自动摘要

正在生成中……

如果你希望在一个命令中 同时推送到多个远程仓库(比如个人账号和工作账号),这里有几种做法:


✅ 方法一:使用 Git 的多 remote 分组(推荐方式)

你可以创建一个 remote 的 push group,让 git push all 自动推送到多个远程。

1. 修改 .git/config 添加一个 push group:

[remote "origin"]
    url = git@github.com-personal:user/repo.git
    fetch = +refs/heads/*:refs/remotes/origin/*

[remote "work"]
    url = git@github.com-work:workuser/repo.git
    fetch = +refs/heads/*:refs/remotes/work/*

[remote "all"]
    url = git@github.com-personal:user/repo.git
    url = git@github.com-work:workuser/repo.git

这个配置中:

  • remote "origin" 是个人账号
  • remote "work" 是工作账号
  • remote "all" 是组合 remote,包含两个 url

2. 使用命令推送到全部:

git push all main

这条命令会依次将当前分支推送到:

  • 个人仓库(origin)
  • 工作仓库(work)

✅ 方法二:使用 Git alias 创建自定义命令

打开全局配置:

git config --global alias.pushall '!git push origin && git push work'

之后在任何项目中运行:

git pushall

等同于:

git push origin
git push work

如果只在某个项目中使用,改为项目内执行:

git config alias.pushall '!git push origin && git push work'

✅ 方法三:手动脚本(适合多个项目批量推送)

创建一个 shell 脚本:

#!/bin/bash
git push origin "$1"
git push work "$1"

保存为 git-push-both.sh,加执行权限:

chmod +x git-push-both.sh

用法:

./git-push-both.sh main

💡 小结

  • 方法一 | 最干净,直接用 Git 内建机制 | ✅✅✅
  • 方法二 | 简洁,适合自己习惯命令行 | ✅✅
  • 方法三 | 灵活,适合多个项目或自定义逻辑 | ✅
本文收录于