# Git Gogs 代码自动同步 > 多种方案实现本地代码与 Gogs 仓库的自动同步,减少手动操作 > 最后更新: 2026-10-08 > Gogs 仓库: https://git.zhonjin.com:40717/steven_roc/git_gog_code_sync ## 方案概览 | 方案 | 适用场景 | 实时性 | |------|----------|--------| | Git Hook 自动 Push | 本地提交后自动推送,单人多设备 | 提交即同步 | | 定时 Cron/任务计划 | 定时双向同步,服务器↔开发机 | 分钟级 | | 文件监听(inotify/fswatch) | 保存即同步,无需等待 | 秒级实时 | | Git Bundle 离线同步 | 不联网环境,U盘介质传输 | 手动触发 | | rsync + Git 混合 | 大文件+代码一起同步 | 分钟级 | ## 文件说明 - `Git代码自动同步详细说明.md` — 完整技术方案文档,包含所有方案的实现步骤、脚本示例和注意事项 - `README.md` — 本文件,项目概览 ## 快速开始 ### 方案 1:Git Hook(推荐单人使用) ```bash cd /path/to/your/repo # 创建 post-commit hook cat > .git/hooks/post-commit << 'HOOK' #!/bin/bash git push origin $(git branch --show-current) 2>&1 | tee -a .git/hooks/push.log HOOK chmod +x .git/hooks/post-commit ``` ### 方案 2:Cron 定时同步 ```bash # 每 5 分钟自动 pull + push */5 * * * * cd /path/to/repo && git pull --rebase origin main && git push origin main >> /var/log/git-sync.log 2>&1 ``` ### 方案 3:文件监听实时同步 ```bash # 需要 inotify-tools inotifywait -m -r -e close_write,move,create,delete /path/to/repo | while read dir events file; do cd /path/to/repo git add -A git diff --cached --quiet || { git commit -m "auto sync: $(date '+%Y-%m-%d %H:%M:%S')" git push origin main } done ``` ## 前提条件 1. **SSH Key 免密配置**:确保 `ssh -T git@git.zhonjin.com` 能通过认证 2. **Git 基本配置**:`git config user.name` 和 `user.email` 已设置 3. **远程仓库已创建**:在 Gogs 上新建空仓库(不勾选初始化) ## 安全提示 - Access Token 定期轮换,避免泄露 - 敏感文件(密钥、密码)加入 `.gitignore` - 自动 push 前确认无敏感信息提交 --- *Gogs 服务器: https://git.zhonjin.com:40717*