DevToolBoxGRATIS
Blog

Git Rebase vs Merge: Cuándo usar cada uno

12 minpor DevToolBox

Entender la diferencia entre git rebase y git merge es esencial para todo desarrollador.

Como funciona Git Merge

Git merge crea un nuevo commit de merge con dos padres.

Al ejecutar git merge feature, Git encuentra el ancestro comun.

Como funciona Git Rebase

Git rebase reescribe el historial.

Git identifica el ancestro comun y re-aplica los commits uno a uno.

Comparacion visual

BEFORE (both branches have diverged from common ancestor C2):

          C5---C6---C7  (feature)
         /
  C1---C2---C3---C4     (main)

AFTER git merge feature (from main):

          C5---C6---C7
         /            \
  C1---C2---C3---C4----M8  (main) ← merge commit M8 has 2 parents
                            (feature still points to C7)

AFTER git rebase main (from feature):

  C1---C2---C3---C4                     (main)
                   \
                    C5'---C6'---C7'     (feature) ← new commits (different SHAs)

  Then fast-forward merge:
  C1---C2---C3---C4---C5'---C6'---C7'  (main, feature) ← linear history

Comparacion de funciones

Aspectogit mergegit rebase
HistorialPreserva todo el historialHistorial lineal
SHA de commitsSHA originales preservadosNuevos SHA creados
SeguridadNo destructivoDestructivo
Resolucion de conflictosResolver una vezResolver por commit
Para equiposSeguro en ramas compartidasPeligroso en ramas compartidas
RevertirFacilDificil
git bisectRuidoso con mergesHistorial limpio
GrafoGrafo complejoLinea limpia

Git Merge en detalle

Fast-Forward Merge

Cuando la rama destino no tiene nuevos commits.

# Fast-forward merge (no merge commit created)
git checkout main
git merge feature

# Before:
# C1---C2 (main)
#        \
#         C3---C4 (feature)

# After:
# C1---C2---C3---C4 (main, feature)
# main pointer simply moved forward

Merge de tres vias

Cuando ambas ramas han divergido.

# Three-way merge (creates merge commit)
git checkout main
git merge feature

# Before:
#        C3---C4 (feature)
#       /
# C1---C2---C5---C6 (main)

# After:
#        C3---C4
#       /       \
# C1---C2---C5---C6---M7 (main)  ← merge commit M7

--no-ff

Fuerza la creacion de un commit de merge.

# Force merge commit even when fast-forward is possible
git checkout main
git merge --no-ff feature

# Before:
# C1---C2 (main)
#        \
#         C3---C4 (feature)

# After (with --no-ff):
# C1---C2---------M5 (main)  ← merge commit preserves branch history
#        \       /
#         C3---C4 (feature)

# After (without --no-ff, default):
# C1---C2---C3---C4 (main, feature)  ← no evidence of branch

Git Rebase en detalle

Rebase basico

Re-aplica commits sobre la rama destino.

# Basic rebase workflow
git checkout feature
git rebase main

# Before:
#        C3---C4 (feature)
#       /
# C1---C2---C5---C6 (main)

# After rebase:
#                     C3'---C4' (feature)  ← new commits!
#                    /
# C1---C2---C5---C6 (main)

# Then merge (fast-forward):
git checkout main
git merge feature
# C1---C2---C5---C6---C3'---C4' (main, feature)  ← linear!

Rebase interactivo

Modificar, comprimir, reordenar o eliminar commits.

# Interactive rebase - clean up last 4 commits
git rebase -i HEAD~4

# Editor opens with:
pick abc1234 Add user model
pick def5678 Fix typo in user model
pick ghi9012 Add user validation
pick jkl3456 Fix validation edge case

# Change to:
pick abc1234 Add user model
fixup def5678 Fix typo in user model        # squash into previous, discard message
pick ghi9012 Add user validation
fixup jkl3456 Fix validation edge case      # squash into previous, discard message

# Result: 2 clean commits instead of 4
# "Add user model" (includes typo fix)
# "Add user validation" (includes edge case fix)

# Interactive rebase commands:
# pick   = use commit as-is
# reword = use commit but edit message
# edit   = use commit but stop for amending
# squash = meld into previous commit (keep message)
# fixup  = meld into previous commit (discard message)
# drop   = remove commit entirely

--onto Rebase

Rebase un subconjunto de commits.

# --onto: Move a branch to a different base
# Scenario: feature-b was branched from feature-a by mistake
#           You want feature-b based on main instead

#        D---E (feature-b)
#       /
# A---B---C (feature-a)
#     |
#     F---G (main)

git rebase --onto main feature-a feature-b

# Result:
#     D'---E' (feature-b)  ← now based on main
#    /
# A---B---C (feature-a)
#     |
#     F---G (main)

Resolucion de conflictos

Ambos pueden producir conflictos.

Conflictos Merge

Todos los conflictos a la vez.

# Merge conflict workflow
git checkout main
git merge feature
# CONFLICT (content): Merge conflict in src/app.ts
# Automatic merge failed; fix conflicts and then commit

# 1. Open conflicting files and resolve
# 2. Stage resolved files
git add src/app.ts
# 3. Complete the merge
git commit  # creates merge commit with conflict resolution

# Abort merge if needed
git merge --abort

Conflictos Rebase

Conflictos por commit.

# Rebase conflict workflow
git checkout feature
git rebase main
# CONFLICT in commit C3: Merge conflict in src/app.ts

# 1. Resolve conflict in src/app.ts
git add src/app.ts
# 2. Continue rebase to next commit
git rebase --continue
# May hit another conflict in C4...

# CONFLICT in commit C4: Merge conflict in src/utils.ts
git add src/utils.ts
git rebase --continue

# Abort rebase if it gets too complex
git rebase --abort  # returns to pre-rebase state

# Skip a problematic commit during rebase
git rebase --skip

Estrategias de workflow

Workflow basado en Merge

El workflow mas comun.

# GitHub Flow (merge-based)
git checkout -b feature/add-auth
# ... make commits ...
git push -u origin feature/add-auth
# Open PR on GitHub
# Review + approve
# Click "Merge pull request" (creates merge commit)
# Or "Squash and merge" (single commit)

Workflow Rebase y luego Merge

Rebase para actualizar, luego merge.

# Rebase-before-merge workflow
git checkout feature/add-auth
# ... make commits ...

# Before opening PR, update with latest main
git fetch origin
git rebase origin/main

# Force push (safe because it's your own branch)
git push --force-with-lease origin feature/add-auth

# Open PR on GitHub
# Merge with --no-ff to record integration point
git checkout main
git merge --no-ff feature/add-auth

Workflow Squash and Merge

Combina todos los commits en uno.

# Squash and merge (via GitHub UI or CLI)
git checkout main
git merge --squash feature/add-auth
git commit -m "feat: add authentication system"

# Before:
# main: A---B---C
# feature: A---B---D---E---F---G

# After squash-merge:
# main: A---B---C---H  ← H contains all changes from D+E+F+G
# (feature branch can be deleted)

La regla de oro del Rebase

Nunca hacer rebase de commits ya pusheados a una rama compartida.

# DANGEROUS: Rebasing a shared branch
git checkout shared-feature
git rebase main
git push --force  # !! This rewrites history for everyone!

# SAFE: Rebasing your own local branch
git checkout my-local-feature
git rebase main
# No push yet, or push --force-with-lease to your own branch

# SAFE: Using --force-with-lease instead of --force
git push --force-with-lease origin my-feature
# Fails if remote has commits you haven't seen

Mejores practicas

Git Rebase vs Merge Best Practices:

1. Use merge for integrating feature branches into main
   - Creates clear integration points
   - Safe for shared branches
   - Easy to revert entire features

2. Use rebase to keep feature branches up-to-date
   - git rebase main (before opening PR)
   - Creates clean, linear history
   - Makes code review easier

3. Use interactive rebase to clean up before PR
   - Squash fixup commits
   - Reword unclear commit messages
   - Drop debugging commits

4. Use git pull --rebase as default
   - Avoids unnecessary merge commits
   - git config --global pull.rebase true

5. Never rebase shared/pushed commits
   - Only rebase your own unpushed work
   - Use --force-with-lease, never --force

6. Use squash-merge for feature branches
   - One clean commit per feature on main
   - Detailed commits preserved in PR history

7. Use --no-ff for important merges
   - Preserves the fact that a branch existed
   - Makes git log --first-parent useful

Preguntas frecuentes

Cuando usar rebase vs merge?

Rebase para actualizar localmente, merge para integrar.

Es peligroso el rebase?

En ramas compartidas si, localmente no.

Que es squash and merge?

Combina todos los commits en uno.

Se puede deshacer un rebase?

Si, con git reflog.

Rebase o merge para equipos?

Enfoque hibrido recomendado.

Que es git pull --rebase?

Rebase en lugar de merge al hacer pull.

Herramientas y guias relacionadas

𝕏 Twitterin LinkedIn
¿Fue útil?

Mantente actualizado

Recibe consejos de desarrollo y nuevas herramientas.

Sin spam. Cancela cuando quieras.

Prueba estas herramientas relacionadas

{ }JSON Formatter

Artículos relacionados

Git Rebase vs Merge: Cuándo usar cada uno (con ejemplos visuales)

Entiende la diferencia entre git rebase y merge. Aprende cuándo usar cada uno y evita errores comunes.

Git Commands Cheat Sheet: Comandos esenciales para todo desarrollador

Cheat sheet completo de comandos Git: configuración, ramas, merge, rebase, stash y flujos avanzados.

Estrategias de ramificacion Git: GitFlow vs Trunk-Based vs GitHub Flow

Compara las estrategias GitFlow, Trunk-Based Development y GitHub Flow. Estructuras de ramas, flujos de merge, integracion CI/CD y como elegir la estrategia correcta.