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

误强制推送覆盖远程Git仓库后,如何恢复原有分支?

问题

队友创建了一个远程仓库,已推送文件x、y、z,远程仓库最初有2个她提交的commit。我在本地编辑了相同文件但未同步远程,她要求我在她的修改之上推送我的变更。

我在本地编辑文件的文件夹执行了以下命令:

git init
git remote add origin {remote repo clone link}
git add .
git commit -m "initial commit by me"
git push --setupstream origin master

推送被拒绝,错误信息如下:

fatal: helper error (-1): Cannot access a disposed object.
To ********************************
 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to '***************************'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

添加-f参数强制推送后,远程分支只剩我自己的1个commit,请问能否恢复这个远程分支?

可以恢复,操作步骤如下:
  • 找回丢失的commit哈希
    要么让队友在她的本地仓库执行git log,复制那2个原始commit的哈希值;要么如果能访问远程仓库的命令行,执行git reflog show master,找到被覆盖前的最新commit哈希。

  • 本地修复并推送回远程

    1. 拉取远程当前状态:git fetch origin
    2. 创建临时分支保存你的commit:git checkout -b my-temp origin/master
    3. 切换回master分支,重置到远程丢失的commit(假设哈希是abc1234):git reset --hard abc1234
    4. 合并你的临时分支:git merge my-temp,出现冲突就手动解决后提交
    5. 强制推送到远程:git push -f origin master
  • 后续注意事项

    • 下次不要直接本地git init后关联远程,正确流程是先git clone远程仓库再修改
    • 推送前务必先git pull拉取远程最新变更,解决冲突后再推送,非必要不要用git push -f

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 10:33:58