今天提交代码,发现
git push origin master
! [rejected] master -> master (non-fast-forward)
error: failed to push some refs to
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.
然后那句先 git pull一下把,有提示:
* branch master -> FETCH_HEAD
hint: You have divergent branches and need to specify how to reconcile them.
hint: You can do so by running one of the following commands sometime before
hint: your next pull:
hint:
hint: git config pull.rebase false # merge (the default strategy)
hint: git config pull.rebase true # rebase
hint: git config pull.ff only # fast-forward only
hint:
hint: You can replace "git config" with "git config --global" to set a default
hint: preference for all repositories. You can also pass --rebase, --no-rebase,
hint: or --ff-only on the command line to override the configured default per
hint: invocation.
fatal: Need to specify how to reconcile divergent branches.
根据这个提示,那就可以解决问题:
git pull --rebase
Successfully rebased and updated refs/heads/master.
然后顺利 push
下面解释一下提示里面意思:
提示说明在进行 git pull
时,本地分支和远程分支有分歧(divergent branches)。Git 无法自动决定如何将本地和远程的更改合并,所以需要明确指定如何处理这种情况。有三种选择:
-
合并(Merge): 默认情况下,
git pull
会执行合并操作(merge),但如果之前配置了 rebase 或者 fast-forward,Git 会提示确认如何处理。要明确使用合并策略,可以运行:git config pull.rebase false
这会设置 Git 在进行
git pull
时使用默认的合并策略。 -
变基(Rebase): 如果希望将本地更改应用到远程分支的基础上(即“变基”),可以设置:
git config pull.rebase true
这会设置 Git 在
git pull
时进行变基操作,保持更整洁的历史。 -
仅快速前进(Fast-forward only): 如果只希望在远程分支没有本地分支之外的提交时执行拉取(即只有快速前进的情况),可以设置:
git config pull.ff only
这样,如果分支有分歧且无法执行快速前进合并,
git pull
会失败。
如果希望将上述设置应用到所有仓库,可以使用 --global
参数:
- 合并:
git config --global pull.rebase false
- 变基:
git config --global pull.rebase true
- 快速前进:
git config --global pull.ff only
或者,也可以在单次 git pull
时,使用命令行参数来临时指定:
- 使用合并:
git pull --no-rebase
- 使用变基:
git pull --rebase
- 使用快速前进:
git pull --ff-only
选择其中一个方案,根据需要的工作流来处理即可。 ^_^