Rebase the current feature branch onto the latest target branch (usually master/main), keeping a linear commit history.
Use Cases
- The feature branch is behind master and needs to synchronize the latest code
- Keep the commit history clean before submitting an MR/PR
- Avoid using
git mergeto generate merge commits
Pre-checks
-
Confirm the current branch status:
git branch -v git status -
Confirm the working tree is clean (no uncommitted changes)
Rebase Workflow
1. Fetch the latest code
git fetch origin <目标分支>
2. Perform the Rebase
git rebase origin/<目标分支>
3. Resolve conflicts (if any)
If conflicts occur, handle them as follows:
-
View conflicting files:
git status -
View conflict details:
grep -n "<<<<<<< HEAD\|=======\|>>>>>>>" <冲突文件> -
Conflict resolution strategies:
-
Keep the target branch version (ours):
git checkout --ours <文件路径> -
Keep the current branch version (theirs):
git checkout --theirs <文件路径> -
Manually edit: Directly modify the conflicting files and remove the conflict markers
-
-
Mark the conflict as resolved:
git add <文件路径> -
Continue the rebase:
git rebase --continueIn non-interactive environments or automated execution, avoid
rebase --continuehanging after opening the editor. You can temporarily disable the editor:GIT_EDITOR=true git rebase --continueIf the command is already hanging due to the editor, first confirm the current process and rebase state, then terminate the stuck editor process; do not abort the rebase or repeatedly run commands that would rewrite the state.
-
If you need to abort the rebase:
git rebase --abort
4. Push the updates
git push origin <当前分支> --force-with-lease
Note: You must use
--force-with-leaseto safely force push
Common Issues
Conflict Resolution Principles
- Version number conflicts: Usually keep the newer version
- API changes: Analyze based on the specific situation and ask the user for their intent
- Configuration changes: Assess the impact of the change and choose the appropriate version
Safety Recommendations
- Before rebasing, ensure you have a backup or a branch that has already been pushed
- Do not rebase public branches (such as master)
- Use
--force-with-leaseinstead of--forceto push - If uncertain, ask the user to choose first
Complete Example
# 1. 检查状态
git branch -v
git status
# 2. 获取最新代码
git fetch origin master
# 3. 执行 rebase
git rebase origin/master
# 4. 解决冲突(如需要)
# - 查看冲突: git status
# - 保留 ours/theirs 或手动编辑
# - git add <文件>
# - git rebase --continue
# 5. 推送
git push origin feature-branch --force-with-lease