一次性同步到另一个服务器,然后以后仍只在原服务器开发

方案 A:只把某个分支(含历史)一次性推过去(最常用)

# 1) 在当前仓库添加一个临时远端(建议命名 tmp)
git remote add tmp ssh://git@other.example.com/group/repo.git
# 或者 HTTPS:
# git remote add tmp https://other.example.com/group/repo.git
 
# 2) 推送你要给对方的分支(例如 main)
git push tmp main:main
 
# 可选:如果还要把标签一起给过去
git push tmp --tags
 
# 3) 推完就删掉临时远端,避免后续误推
git remote remove tmp

以后你继续对原来的 origin 开发、推送即可。

方案 B:把所有分支与标签一次性同步(保留完整历史)

git remote add tmp ssh://git@other.example.com/group/repo.git
git push tmp --all      # 推送所有分支
git push tmp --tags     # 推送所有标签
git remote remove tmp

方案 C:完整镜像(包含所有 refs;谨慎)

如果想让目标仓库与当前仓库一模一样(包括远程跟踪分支、notes 等),用 --mirror。注意:这会覆盖目标端的同名引用,目标最好是空仓库。

git remote add tmp ssh://git@other.example.com/group/repo.git
git push tmp --mirror
git remote remove tmp

方案 D:只给“最新代码快照”,不包含历史(代码投递/一次性交付)

若你只想给“当前代码”而不暴露历史,用 git archive 打包:

# 生成当前 HEAD 的源码包(无 .git 历史)
git archive --format=tar.gz -o repo-$(date +%F).tar.gz HEAD

把生成的压缩包上传到对方服务器的仓库/制品库即可(这不是 Git 推送;适合只交付源码快照的场景)。

方案 E:离线“一次性”同步(对方再自行还原并推送)

git bundle 做一个“一次性可克隆”的文件:

# 打包整个仓库(含所有分支与历史)
git bundle create repo-$(date +%F).bundle --all
 
# 对方机器上:
git clone repo-2025-09-04.bundle newrepo
# 然后在 newrepo 内配置自己的远端并首次推送
git remote add origin ssh://git@other.example.com/group/repo.git
git push -u origin --all
git push origin --tags

防止后续“误同步”的小技巧

  • 本地侧:按上面做法,推送结束后 git remote remove tmp,以后自然推不到那个服务器。

  • 目标服务器侧(可选):把项目标记为“Archived/只读”或保护分支,防止别人再推。

你可能会关心的细节

  • 目标仓库为空:以上 A/B/C 都没问题;若非空且历史不同,--mirror 会覆盖,普通 push 可能被拒(需合并或强推)。强推请用 --force-with-lease,但仅在你明确想覆盖时才用。

  • Git LFS:如果用了 LFS,首次到另一台服务器还需推 LFS 对象:

    git lfs push tmp --all

    并确保目标端启用了 LFS。

  • 子模块:记得同步子模块仓库,或在目标端更新子模块 URL;打包快照时可用:

    git submodule update --init --recursive
    git archive ...  # 但注意 archive 不会自动把子模块内容打进去
  • 只给单一分支:方案 A 就是;若多分支一起给用方案 B;全量镜像用 C。

  • 只给源码、不暴露历史:用方案 D(archive)最干净。

如果你告诉我这次要“只给哪个分支/是否要历史/是否用 LFS/有没有子模块”,我可以把对应的命令替你拼成一组可直接复制粘贴的脚本。