Git 代码自动同步是指通过自动化手段,将本地代码变更自动推送到远程仓库(或反之),减少手动操作步骤,保证多设备/多人协作时代码始终一致。
| 概念 | 说明 |
|---|---|
| 远程仓库(Remote) | GitHub / GitLab / Gitee / GOG 等托管平台上的仓库 |
| 本地仓库(Local) | 开发者机器上的 .git 仓库 |
| Push | 本地 → 远程,上传自己的提交 |
| Pull | 远程 → 本地,拉取他人的更新 |
| Fetch + Merge | Pull 的底层实现,先拉取再合并 |
| Hook | Git 生命周期回调,可在特定事件时自动触发脚本 |
适用场景:本地提交后自动推送到远程,适合单人多设备同步。
实现步骤:
# 1. 进入仓库目录
cd /path/to/your/repo
# 2. 创建 post-commit hook
cat > .git/hooks/post-commit << 'EOF'
#!/bin/bash
# 提交后自动推送
git push origin $(git branch --show-current) 2>&1 | tee -a .git/hooks/push.log
EOF
# 3. 赋予执行权限
chmod +x .git/hooks/post-commit
注意:
适用场景:定时双向同步,适合服务器和开发机之间保持同步。
Linux Cron 实现:
# 编辑 crontab
crontab -e
# 每 5 分钟自动 pull + push
*/5 * * * * cd /path/to/repo && git pull --rebase origin main && git push origin main >> /var/log/git-sync.log 2>&1
Windows 任务计划实现(PowerShell):
# 创建同步脚本 sync.ps1
Set-Location "C:\path\to\repo"
git pull --rebase origin main
git push origin main
# 使用 Windows 任务计划程序创建定时任务
$action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-File C:\path\to\sync.ps1"
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 5)
Register-ScheduledTask -TaskName "GitAutoSync" -Action $action -Trigger $trigger
适用场景:文件保存后实时同步,无需等待 cron 周期。
Linux(inotifywait):
#!/bin/bash
# auto-sync.sh
REPO_DIR="/path/to/repo"
BRANCH="main"
inotifywait -m -r -e close_write,move,create,delete "$REPO_DIR" |
while read -r directory events filename; do
cd "$REPO_DIR"
git add -A
git diff --cached --quiet || {
git commit -m "auto sync: $(date '+%Y-%m-%d %H:%M:%S')"
git push origin "$BRANCH"
}
done
macOS(fswatch):
brew install fswatch
fswatch -r /path/to/repo --event Updated --event Created --event Removed |
while read event; 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
适用场景:两台机器不联网,通过 U 盘等介质同步。
# 机器 A:打包变更
git bundle create /media/usb/repo.bundle --all
# 机器 B:从 bundle 拉取
git pull /media/usb/repo.bundle main
适用场景:大量非代码文件(如编译产物)也需要一起同步。
#!/bin/bash
# 1. 先 git 同步代码
cd /path/to/repo
git add -A && git commit -m "auto sync" && git push origin main
# 2. 再 rsync 同步构建产物
rsync -avz --exclude='.git' /path/to/repo/ user@remote:/path/to/repo/
自动同步的前提是免密认证:
# 1. 生成 SSH Key(如果没有)
ssh-keygen -t ed25519 -C "your_email@example.com"
# 2. 复制公钥到远程平台
cat ~/.ssh/id_ed25519.pub
# 粘贴到 GitHub/GitLab/Gitee 的 SSH Keys 设置中
# 3. 测试连接
ssh -T git@github.com
自动同步最大的风险是冲突。推荐策略:
| 场景 | 策略 |
|---|---|
| 单人多设备 | 使用 pull --rebase,避免无意义 merge commit |
| 多人协作 | 不自动 push,改为 CI/CD 自动 pull 和测试 |
| 纯文档类 | 可接受 occasional conflict,用 ours 或 theirs 策略 |
| 二进制文件 | 使用 Git LFS 或改用 rsync 方案 |
自动解决冲突的配置(仅限单人场景):
# 优先使用远程版本
git config pull.rebase true
git config rerere.enabled true
# 或者冲突时自动选择一方
git config merge.strategy.option theirs # 远程优先
#!/bin/bash
# git-auto-sync.sh - 完整的自动同步脚本
# 用法: ./git-auto-sync.sh [仓库路径] [远程名] [分支名]
REPO_DIR="${1:-.}"
REMOTE="${2:-origin}"
BRANCH="${3:-main}"
LOG_FILE="$REPO_DIR/.git/auto-sync.log"
log() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" >> "$LOG_FILE"
}
cd "$REPO_DIR" || exit 1
# 检查是否有未提交的变更
if [[ -n "$(git status --porcelain)" ]]; then
git add -A
git commit -m "auto sync: $(date '+%Y-%m-%d %H:%M:%S')"
log "Committed local changes"
fi
# 拉取远程更新(rebase 方式)
if git pull --rebase "$REMOTE" "$BRANCH" >> "$LOG_FILE" 2>&1; then
log "Pull success"
else
log "Pull failed - conflict?"
git rebase --abort
exit 1
fi
# 推送本地提交
if git push "$REMOTE" "$BRANCH" >> "$LOG_FILE" 2>&1; then
log "Push success"
else
log "Push failed"
exit 1
fi
.gitignore 排除git rebase -i 整理| 你的情况 | 推荐方案 |
|---|---|
| 单人,2台设备,偶尔同步 | 方案2:Cron 定时 Pull |
| 单人,实时同步需求 | 方案3:文件监听自动同步 |
| 多人协作 | 不建议自动 push,改为 CI/CD 自动测试 |
| 离线环境 | 方案4:Git Bundle |
| 大文件 + 代码混合 | 方案5:rsync + Git |
文档生成时间:2026-10-02