rebase Git Command Guide
The git rebase command reapplies commits on top of another base tip, allowing you to rewrite commit history, integrate changes from other branches, and maintain a linear project history. It moves or combines a sequence of commits to a new base commit.
git rebase Syntax:
Section titled “git rebase Syntax:”git rebase [-i | --interactive] [<options>] [--exec <cmd>] [--onto <newbase> | --keep-base] [<upstream> [<branch>]]git rebase [-i | --interactive] [<options>] [--exec <cmd>] [--onto <newbase>] --root [<branch>]git rebase (--continue|--skip|--abort|--quit|--edit-todo|--show-current-patch)Rebase Modes:
Section titled “Rebase Modes:”| Mode | Description |
|---|---|
standard | Reapply commits on new base (default) |
--interactive, -i | Interactive rebase with manual control |
--root | Rebase all commits from repository root |
Base Selection Options:
Section titled “Base Selection Options:”| Option | Description |
|---|---|
--onto <newbase> | Rebase onto different base commit |
--keep-base | Use upstream as base (default behavior) |
<upstream> | Branch/commit to rebase onto |
Interactive Options:
Section titled “Interactive Options:”| Option | Description |
|---|---|
--interactive, -i | Start interactive rebase |
--exec <cmd> | Execute command after each commit |
--rebase-merges | Preserve merge commits |
--preserve-merges | Preserve merge commits (deprecated) |
History Modification Options:
Section titled “History Modification Options:”| Option | Description |
|---|---|
--squash | Squash commits during rebase |
--autosquash | Automatically squash fixup commits |
--autostash | Stash working changes before rebase |
--no-autostash | Don’t stash working changes |
Safety and Control Options:
Section titled “Safety and Control Options:”| Option | Description |
|---|---|
--fork-point | Use merge-base —fork-point |
--no-fork-point | Don’t use fork-point detection |
--force-rebase, -f | Force rebase even if unnecessary |
--no-ff | Always create merge commit |
--ff | Allow fast-forward (default) |
Conflict Resolution Options:
Section titled “Conflict Resolution Options:”| Option | Description |
|---|---|
--continue | Continue after resolving conflicts |
--skip | Skip current patch |
--abort | Abort rebase and restore original |
--quit | Stop rebase but keep current state |
--edit-todo | Edit interactive rebase todo list |
Output and Information Options:
Section titled “Output and Information Options:”| Option | Description |
|---|---|
--verbose, -v | Verbose output |
--quiet, -q | Suppress output |
--stat | Show diffstat of changes |
--no-stat | Don’t show diffstat |
--show-current-patch | Show current patch being applied |
Parameters:
Section titled “Parameters:”| Parameter | Description |
|---|---|
<upstream> | Branch/commit to rebase onto |
<branch> | Branch to rebase (default: current) |
<newbase> | Target base for —onto option |
Understanding Rebase Operations:
Section titled “Understanding Rebase Operations:”Rebase Process Flow:
Section titled “Rebase Process Flow:”Before Rebase: A---B---C---D (main) \ E---F (feature)
After Rebase: A---B---C---D (main) \ E'---F' (feature)Interactive Rebase Commands:
Section titled “Interactive Rebase Commands:”Interactive Commands: pick <commit> = use commit reword <commit> = use commit, but edit the commit message edit <commit> = use commit, but stop for amending squash <commit> = use commit, but meld into previous commit fixup <commit> = like "squash", but discard this commit's log message exec <command> = run command (the rest of the line) using shell drop <commit> = remove commitRebase Strategies:
Section titled “Rebase Strategies:”Merge Strategy (default): Preserves merge commits Shows complete history Can create complex graphs
Rebase Strategy: Creates linear history Easier to follow Hides merge informationBasic Rebase Examples:
Section titled “Basic Rebase Examples:”Standard Rebasing:
Section titled “Standard Rebasing:”# Rebase current branch onto maingit rebase main
# Rebase feature branch onto developgit rebase develop feature-branch
# Rebase with upstream trackinggit rebase origin/main
# Rebase onto specific commitgit rebase abc123Interactive Rebasing:
Section titled “Interactive Rebasing:”# Interactive rebase last 3 commitsgit rebase -i HEAD~3
# Interactive rebase onto different basegit rebase -i --onto main feature-branch
# Interactive rebase from rootgit rebase -i --rootAdvanced Rebasing:
Section titled “Advanced Rebasing:”# Rebase with autosquashgit rebase -i --autosquash main
# Rebase with exec commandsgit rebase -i --exec "make test" main
# Rebase preserving mergesgit rebase -i --rebase-merges mainInteractive Rebase Scenarios:
Section titled “Interactive Rebase Scenarios:”Commit History Cleanup:
Section titled “Commit History Cleanup:”# Clean up messy commit historygit rebase -i HEAD~10
# Interactive rebase todo list:pick 123456 Initial commitsquash 234567 Fix typofixup 345678 Minor fixreword 456789 Update messageedit 567890 Amend commitBranch Integration:
Section titled “Branch Integration:”# Integrate feature branch cleanlygit checkout featuregit rebase -i main
# Resolve conflicts during rebasegit rebase --continue # After fixing conflictsgit rebase --skip # Skip problematic commitgit rebase --abort # Cancel rebaseComplex History Rewriting:
Section titled “Complex History Rewriting:”# Split large commit into smaller onesgit rebase -i HEAD~1
# Edit commit during rebaseedit abc123 # Stop at this commit# Make changesgit add .git commit --amendgit rebase --continueConfiguration and Best Practices:
Section titled “Configuration and Best Practices:”Git Configuration for Rebase:
Section titled “Git Configuration for Rebase:”# Configure default rebase behaviorgit config pull.rebase true # Rebase on pullgit config rebase.stat true # Show rebase statsgit config rebase.autoSquash true # Auto-squash fixup commitsgit config rebase.autoStash true # Auto-stash on rebase
# Configure rebase backendsgit config rebase.backend merge # Use merge backendgit config rebase.backend apply # Use apply backend
# Configure rebase for specific branchesgit config branch.feature.rebase truegit config branch.main.rebase interactiveSafe Rebasing Practices:
Section titled “Safe Rebasing Practices:”# Always backup before complex rebasesgit branch backup-branch
# Check rebase statusgit status
# Verify rebase completed successfullygit log --oneline -10
# Clean up backup after verificationgit branch -D backup-branchRebase vs Merge Decision:
Section titled “Rebase vs Merge Decision:”# Use rebase for:# - Feature branches before merging# - Cleaning up local commit history# - Maintaining linear project history
# Use merge for:# - Preserving complete history# - Public/shared branches# - When merge commits add value
# Quick decision guide:if [ "$BRANCH_TYPE" = "feature" ] && [ "$SHARED" = "false" ]; then git rebase mainelse git merge mainfiIntegration with Development Workflows:
Section titled “Integration with Development Workflows:”Feature Branch Workflow:
Section titled “Feature Branch Workflow:”#!/bin/bash# Feature branch development with rebase
feature_workflow() { local feature_branch="$1" local base_branch="${2:-main}"
# Create and switch to feature branch git checkout -b "$feature_branch" "$base_branch"
# Development work... # Make commits...
# Regular rebase to stay updated git fetch origin git rebase "origin/$base_branch"
# Interactive cleanup before merge git rebase -i "$base_branch"
# Final rebase before PR git rebase -i --autosquash "$base_branch"}
feature_workflow "user-authentication" "develop"Pull Request Preparation:
Section titled “Pull Request Preparation:”# Prepare branch for pull requestprepare_for_pr() { local target_branch="${1:-main}"
echo "Preparing branch for pull request..."
# Fetch latest changes git fetch origin
# Interactive rebase for clean history git rebase -i "origin/$target_branch"
# Run tests after rebase if command -v run-tests >/dev/null 2>&1; then run-tests || { echo "Tests failed after rebase" exit 1 } fi
# Final verification git log --oneline "origin/$target_branch..HEAD" echo "Branch ready for pull request"}
prepare_for_pr "main"Automated Rebase Maintenance:
Section titled “Automated Rebase Maintenance:”# Automated rebase maintenanceautomated_rebase_maintenance() { echo "Performing automated rebase maintenance..."
# Update all feature branches for branch in $(git branch --list "feature/*" | sed 's/*//'); do echo "Updating $branch..."
# Switch to branch git checkout "$branch" 2>/dev/null || continue
# Attempt rebase if git rebase --quiet main; then echo "✓ $branch rebased successfully" else echo "✗ $branch rebase failed - manual intervention needed" git rebase --abort fi done
# Return to main git checkout main}
automated_rebase_maintenanceTroubleshooting Common Issues:
Section titled “Troubleshooting Common Issues:”Rebase Conflicts:
Section titled “Rebase Conflicts:”# Handle merge conflicts during rebaseresolve_rebase_conflicts() { echo "Resolving rebase conflicts..."
# Check conflicted files git status
# Edit conflicted files # Remove conflict markers # Stage resolved files git add resolved-file.txt
# Continue rebase git rebase --continue
# Alternative: Skip this commit # git rebase --skip
# Alternative: Abort rebase # git rebase --abort}
resolve_rebase_conflictsRebase in Progress Issues:
Section titled “Rebase in Progress Issues:”# Handle interrupted rebasehandle_rebase_in_progress() { echo "Handling rebase in progress..."
# Check rebase status if [ -d .git/rebase-apply ] || [ -d .git/rebase-merge ]; then echo "Rebase in progress detected"
# Options: # Continue rebase git rebase --continue
# Skip current commit # git rebase --skip
# Abort rebase # git rebase --abort
# Edit todo list # git rebase --edit-todo else echo "No rebase in progress" fi}
handle_rebase_in_progressRemote Rebase Issues:
Section titled “Remote Rebase Issues:”# Handle rebase with remote branchesremote_rebase_handling() { echo "Handling remote rebase issues..."
# Fetch latest changes git fetch origin
# Check for remote changes if git log --oneline HEAD..origin/main | grep -q .; then echo "Remote has new commits"
# Rebase local changes git rebase origin/main
# Force push if needed (careful!) # git push --force-with-lease origin main else echo "No remote changes" fi}
remote_rebase_handlingPerformance Issues with Large Rebases:
Section titled “Performance Issues with Large Rebases:”# Handle large rebase operationslarge_rebase_optimization() { echo "Optimizing large rebase operation..."
# Use apply backend for large rebases git config rebase.backend apply
# Increase memory limits export GIT_REBASE_MEMORY=1g
# Rebase in smaller chunks git rebase --onto HEAD~50 HEAD~100 # Rebase last 50 commits
# Monitor progress git rebase --verbose
# Clean up after large rebase git gc --aggressive}
large_rebase_optimizationReal-World Usage Examples:
Section titled “Real-World Usage Examples:”Enterprise Development Workflow:
Section titled “Enterprise Development Workflow:”#!/bin/bash# Enterprise rebase workflow with compliance
enterprise_rebase_workflow() { local feature_branch="$1" local compliance_check="$2"
echo "Enterprise rebase workflow for $feature_branch"
# Pre-rebase compliance check if [ -n "$compliance_check" ] && command -v "$compliance_check" >/dev/null 2>&1; then if ! "$compliance_check" "$feature_branch"; then echo "Compliance check failed - aborting rebase" exit 1 fi fi
# Create audit trail audit_file="rebase-audit-$(date +%Y%m%d-%H%M%S).log" echo "Rebase initiated by $(whoami) at $(date)" > "$audit_file" echo "Feature branch: $feature_branch" >> "$audit_file" git log --oneline HEAD~5 >> "$audit_file"
# Perform rebase with logging if git rebase -i --verbose main >> "$audit_file" 2>&1; then echo "Rebase completed successfully" >> "$audit_file"
# Post-rebase validation if command -v validate-rebase >/dev/null 2>&1; then validate-rebase "$feature_branch" >> "$audit_file" fi
echo "✓ Enterprise rebase completed with audit trail: $audit_file" else echo "Rebase failed - check audit log: $audit_file" echo "To abort: git rebase --abort" exit 1 fi}
enterprise_rebase_workflow "secure-auth-feature" "security-compliance-check"CI/CD Pipeline Integration:
Section titled “CI/CD Pipeline Integration:”# Rebase in CI/CD pipelineci_rebase_integration() { echo "CI/CD rebase integration..."
# Only rebase on feature branches if [[ "$CI_COMMIT_REF_NAME" == feature/* ]]; then echo "Rebasing feature branch $CI_COMMIT_REF_NAME"
# Fetch target branch git fetch origin main
# Attempt rebase if git rebase --quiet origin/main; then echo "✓ Rebase successful"
# Run tests on rebased code if ! run-ci-tests; then echo "✗ Tests failed after rebase" git rebase --abort exit 1 fi
# Push rebased branch git push --force-with-lease origin "$CI_COMMIT_REF_NAME"
else echo "✗ Rebase failed - conflicts detected" git rebase --abort
# Create merge commit instead git merge origin/main --no-ff -m "Merge main into $CI_COMMIT_REF_NAME" git push origin "$CI_COMMIT_REF_NAME" fi else echo "Skipping rebase for non-feature branch: $CI_COMMIT_REF_NAME" fi}
ci_rebase_integrationCollaborative Rebase Management:
Section titled “Collaborative Rebase Management:”# Manage rebases in collaborative environmentcollaborative_rebase_management() { local branch="$1" local team_members="$2"
echo "Collaborative rebase management for $branch"
# Check if branch is shared if git branch -r | grep -q "origin/$branch"; then echo "Branch $branch is shared - coordinating rebase"
# Notify team members for member in $team_members; do echo "Notifying $member about rebase of $branch" # send_notification "$member" "Branch $branch is being rebased" done
# Create backup branch git branch "backup/$branch-$(date +%Y%m%d)"
# Perform rebase if git rebase main "$branch"; then echo "✓ Rebase successful"
# Update remote git push --force-with-lease origin "$branch"
# Notify completion for member in $team_members; do # send_notification "$member" "Branch $branch rebased successfully" echo "Notified $member of successful rebase" done else echo "✗ Rebase failed - restoring from backup" git rebase --abort git checkout "backup/$branch-$(date +%Y%m%d)" fi else echo "Branch $branch is local - rebasing directly" git rebase main "$branch" fi}
collaborative_rebase_management "team-feature" "alice bob charlie"What’s the difference between rebase and merge?
Section titled “What’s the difference between rebase and merge?”Rebase creates linear history by replaying commits on new base; merge preserves complete history with merge commits. Rebase for clean history, merge for complete history.
When should I use interactive rebase?
Section titled “When should I use interactive rebase?”Use interactive rebase to clean up commit history before sharing: squash commits, reword messages, reorder commits, or split large commits.
How do I abort a rebase?
Section titled “How do I abort a rebase?”Use git rebase —abort to cancel rebase and restore original branch state. Use git rebase —quit to stop but keep current state.
Can I rebase a shared branch?
Section titled “Can I rebase a shared branch?”Avoid rebasing shared branches as it rewrites history. If necessary, coordinate with team and use —force-with-lease for pushing.
What’s the difference between rebase —onto and regular rebase?
Section titled “What’s the difference between rebase —onto and regular rebase?”Regular rebase replays commits onto upstream; —onto replays commits onto different base commit, useful for complex branch restructuring.
How do I handle rebase conflicts?
Section titled “How do I handle rebase conflicts?”Resolve conflicts by editing files, staging changes with git add, then continue with git rebase —continue. Skip with —skip or abort with —abort.
Can I preserve merge commits during rebase?
Section titled “Can I preserve merge commits during rebase?”Use —rebase-merges to preserve merge commits in interactive rebase. Regular rebase flattens history by default.
What’s the impact of rebase on commit SHAs?
Section titled “What’s the impact of rebase on commit SHAs?”Rebase creates new commits with different SHAs since they have different parents. Original commits remain in reflog until expired.
How do I rebase from repository root?
Section titled “How do I rebase from repository root?”Use git rebase -i —root to rebase all commits from the initial commit. Useful for repository-wide history cleanup.
Can I automate rebase operations?
Section titled “Can I automate rebase operations?”Yes, use scripts for regular rebase maintenance, but always include error handling and backup creation.
What’s the difference between rebase and cherry-pick?
Section titled “What’s the difference between rebase and cherry-pick?”Rebase replays multiple commits onto new base; cherry-pick applies single commit to current branch.
How do I check rebase status?
Section titled “How do I check rebase status?”Use git status to see if rebase is in progress. Check .git/rebase-apply or .git/rebase-merge directories.
Can I edit commits during rebase?
Section titled “Can I edit commits during rebase?”Yes, use edit command in interactive rebase to stop at commits, make changes, amend, then continue.
What’s the safest way to rebase?
Section titled “What’s the safest way to rebase?”Create backup branch first, ensure clean working directory, test after rebase, use —abort if issues occur.
Applications of the git rebase command
Section titled “Applications of the git rebase command”- History Cleanup: Clean up messy commit history before sharing code
- Branch Integration: Integrate feature branches with clean, linear history
- Collaboration: Stay updated with main branch changes during development
- Code Review: Prepare branches for clean pull request submissions
- Repository Maintenance: Maintain linear project history and avoid merge clutter
- Release Preparation: Clean up commit history before releases or deployments