虽然我的回答超出了您的要求,但我认为这实际上是您打算做的。
您使用git reset --soft HEAD^ 撤消了您所做的提交。这会将工作副本返回到您提交之前的状态(因为HEAD 指向您当前的提交,而HEAD^ 指向之前的提交(假设只有一个父级)。
但是现在当您git push 时,您会被告知:
! [rejected] <branch> -> <branch>e (non-fast-forward)
error: failed to push some refs to 'ssh://<remote server>/<remote path>'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
这是说提交没有对齐,它是为了防止你犯错误。错误消息有点误导,您不想按照它的建议去做(拉动以使您的分支同步)。由于您的意图,您只能知道不要这样做。
您可以通过--force(或-f)(*)轻松解决此问题:
git push --force
您可能需要再次设置上游:
git push --force --set-upstream origin <branch>
请注意,如果其他人已经撤消了您的工作,这将产生后果,因为会有不同的提交进行相同的更改(可能)。见https://www.kernel.org/pub/software/scm/git/docs/user-manual.html#problems-With-rewriting-history。
为防止出现任何问题,请只推送到您的分支(而不是某些公共分支 - 例如开发人员将所有功能分支合并到的 development 分支)并确保开放式沟通 在你的团队中。
开发人员通常会将此模式用于我所说的 Friday Afternoon 提交,您希望在周末之前保存您的工作以防硬件故障(但返回到星期一的预提交状态)。
*Friday*
git add --all # To add all files whether they are tracked or not
git commit -m "Friday afternoon commit"
git --set-upstream push # --set-upstream is for if the branch doesn't exist on the remote server
*Monday*
git reset --soft HEAD^
git push -f --set-upstream origin <branch>
与另一个答案中讨论的git revert 相比,这样做的好处是避免了额外的提交。重置将有 2 次提交,这种方式将没有(没有额外的)。 git reset 的优点是它不会重写历史记录,因此更安全,尤其是在您不确定自己在做什么的情况下。
(*) 通常存储库被配置为不允许您这样做以掌握 - 修复分支并创建拉取请求。因为如果你已经阅读了上面的链接,在 master 上重写历史将会产生严重的后果(除非你是唯一一个克隆过该代码的人)。