You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将BitBucket的Git代码同步到GitHub?多分支追踪最优方案咨询

将BitBucket仓库全部分支同步到GitHub的最优方案

一、基础全量同步(手动操作)

如果只需要一次性同步所有分支、标签及历史记录,最直接的方式是使用Git镜像模式:

  1. 克隆BitBucket镜像仓库:
    该命令会完整复刻仓库的所有分支、标签和提交历史,是全量同步的最优初始操作:
    git clone --mirror git@bitbucket.org:<你的用户名>/<目标仓库名>.git
    
  2. 添加GitHub远程仓库:
    进入克隆的镜像仓库目录,将GitHub仓库设为新远程:
    cd <目标仓库名>.git
    git remote add github git@github.com:<你的用户名>/<GitHub仓库名>.git
    
  3. 全量推送到GitHub:
    用--mirror参数推送,会完全同步BitBucket的所有内容,包括分支删除操作:
    git push --mirror github
    

若已有本地仓库,也可替代使用以下命令:

  • 推送所有分支:git push github --all
  • 推送所有标签:git push github --tags
    但镜像模式能保证两边仓库状态完全一致,更适合全量同步场景。

二、长期自动同步(最优持续方案)

手动同步效率低下,推荐用定时任务或CI/CD工具实现自动同步:

1. 本地定时任务(Linux/macOS)

编写同步脚本配合cron定时执行:

  • 创建脚本文件sync-bitbucket-to-github.sh:
    #!/bin/bash
    # 切换到镜像仓库目录
    cd /path/to/your/mirrored-repo
    # 拉取BitBucket最新变更
    git remote update
    # 推送到GitHub
    git push --mirror github
    
  • 给脚本添加执行权限:chmod +x sync-bitbucket-to-github.sh
  • 配置cron定时任务(示例为每小时同步一次):
    执行crontab -e,添加一行:
    0 * * * * /path/to/sync-bitbucket-to-github.sh
    

2. CI/CD自动同步(推荐)

用GitHub Actions或BitBucket Pipelines实现云端自动同步,无需依赖本地机器:
以GitHub Actions为例,在GitHub仓库中创建.github/workflows/sync.yml:

name: 同步BitBucket仓库到GitHub
on:
  schedule:
    - cron: '0 * * * *' # 每小时自动同步一次
  workflow_dispatch: # 支持手动触发同步

jobs:
  sync-repo:
    runs-on: ubuntu-latest
    steps:
      - name: 克隆BitBucket镜像仓库
        uses: actions/checkout@v4
        with:
          repository: <你的BitBucket用户名>/<仓库名>
          ssh-key: ${{ secrets.BITBUCKET_SSH_KEY }}
          fetch-depth: 0
          ref: refs/heads/*
      - name: 配置Git身份
        run: |
          git config --global user.name "你的用户名"
          git config --global user.email "你的邮箱"
      - name: 添加GitHub远程并推送
        run: |
          git remote add github git@github.com:<你的GitHub用户名>/<仓库名>.git
          git push --mirror github
        env:
          GIT_SSH_COMMAND: "ssh -i ${{ secrets.GITHUB_SSH_KEY }}"

注意:需在GitHub仓库的Secrets中添加BITBUCKET_SSH_KEY(访问BitBucket的私钥)和GITHUB_SSH_KEY(访问GitHub的私钥)。

三、关键注意事项

  • 权限配置:确保用于同步的SSH密钥或账号拥有BitBucket的读取权限和GitHub的写入权限。
  • 避免双向修改:建议仅将BitBucket作为唯一开发源,GitHub作为镜像仓库,否则两边同时提交会导致同步冲突。
  • 分支保护:如果GitHub开启了分支保护规则,需确保同步操作拥有强制推送权限(仅在镜像同步场景下安全)。

内容的提问来源于stack exchange,提问作者MagMax

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 17:52:58