问题描述
本地修改代码后正准备push到远程仓库,但是遇到了如下问题:
error: failed to push some refs to 'https://github.com...'
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.
输入git pull
获得
ou@ous-MacBook-Pro demo % git pull
error: cannot pull with rebase: You have unstaged changes.
error: please commit or stash them.
这是因为在执行 git pull 命令时,Git 会自动尝试合并远程仓库的更改和本地仓库的更改,如果本地存在未提交的更改,可能会导致代码冲突或其他问题。输入git pull --rebase origin master
无法解决问题
ou@ous-MacBook-Pro demo % git pull --rebase origin master
error: cannot pull with rebase: You have unstaged changes.
error: please commit or stash them.
解决方案
我选择先保存未提交的更改,使用 git stash 命令将这些更改保存到一个栈中,以便稍后重新应用这些更改。执行以下命令:
# 先保存到一个栈
ou@ous-MacBook-Pro demo % git stash
Saved working directory and index state WIP on main: ...
# 合并远程仓库的更改和本地仓库的更改
ou@ous-MacBook-Pro demo % git pull
# 将更改恢复回来
ou@ous-MacBook-Pro demo % git stash pop
# 提交本地仓库更改
ou@ous-MacBook-Pro demo % git push
至此,问题就解决了。