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

如何实现GitHub仓库更新后自动同步至Ubuntu本地文件夹?

实现GitHub仓库到Ubuntu本地文件夹的同步方案

一、手动运行脚本的方案(完全匹配你的流程)

由于你的本地文件夹已和GitHub仓库关联,核心逻辑是拉取远程仓库的最新代码,具体实现步骤如下:

  1. 编写同步脚本
    创建名为sync_repo.sh的脚本,根据实际场景选择版本:
  • 基础版本(无本地未提交修改时使用):
#!/bin/bash
# 切换到本地仓库的绝对路径
cd /home/your-username/your-local-repo
# 拉取远程最新代码(替换main为你的仓库实际分支名,比如master)
git pull origin main
  • 带本地修改暂存的版本(需保留本地未提交修改时使用):
#!/bin/bash
cd /home/your-username/your-local-repo
# 暂存本地未提交修改
git stash
# 拉取最新代码
git pull origin main
# 恢复之前暂存的修改
git stash pop
  1. 赋予脚本执行权限
    在终端执行命令:
chmod +x sync_repo.sh
  1. 手动触发同步
    每次向GitHub仓库推送新文件后,在Ubuntu终端运行:
./sync_repo.sh

注意事项

  • 替换脚本中的/home/your-username/your-local-repo为你的本地仓库实际路径
  • 分支名main要和GitHub仓库的默认分支保持一致,可在仓库主页查看分支名称
  • 若无需保留本地未提交修改,可直接用git reset --hard origin/main替代git pull(此操作会彻底丢弃本地未提交的所有变更,谨慎使用)

二、进阶:自动触发同步(无需手动运行脚本)

如果之后希望实现推送代码后自动同步,可通过GitHub Webhook实现:

  1. 在Ubuntu上搭建简易Web服务
    用Python Flask快速实现监听服务(需先安装flask:pip install flask),创建webhook_server.py:
from flask import Flask, request
import subprocess
import os

app = Flask(__name__)
REPO_PATH = "/home/your-username/your-local-repo"

@app.route('/sync', methods=['POST'])
def sync_repo():
    # 可添加GitHub签名验证,防止恶意请求
    subprocess.run(["bash", "/path/to/your/sync_repo.sh"], cwd=REPO_PATH)
    return "Sync completed", 200

if __name__ == '__main__':
    # 监听0.0.0.0,端口设为8080(需确保服务器开放该端口)
    app.run(host='0.0.0.0', port=8080)
  1. 配置GitHub Webhook
  • 进入GitHub仓库的Settings -> Webhooks -> Add webhook
  • Payload URL填写:http://你的Ubuntu服务器公网IP:8080/sync
  • Content type选择application/json
  • Which events would you like to trigger this webhook?选择Just the push event
  • 点击Add webhook完成配置
  1. 运行Web服务
    在Ubuntu终端执行:
nohup python3 webhook_server.py &

(用nohup让服务在后台持续运行)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 06:35:28