git reset --hard, checkout ., stash drop, clean -fd y rebase abortado: qué se recupera y qué no, medido con git 2.43.0
con git 2.43.0, un commit perdido por `reset --hard HEAD~1` seguía en HEAD@{1} y `git reset --hard HEAD@{1}` lo devolvió. En un `reset --hard` con tres tipos de cambios, el fichero nuevo con `git add` desapareció del árbol pero su contenido siguió como 1 blob colgante (lo mostró `git fsck` y `fsck --lost-found` dejó 1 fichero); el cambio sin `add` en un fichero seguido no estaba en ningún objeto, y el fichero sin seguimiento no se tocó. `git checkout .` conservó la parte con `add` de un fichero y perdió la parte sin `add` (no estaba en ningún objeto). `git stash drop` dejó el commit WIP en el repositorio como inalcanzable y `git stash apply <hash>` devolvió los cambios; con `stash -u` también volvió el fichero sin seguimiento. `git clean -fd` borró el fichero y el directorio sin seguimiento sin dejar rastro en los objetos; el fichero con `add` y el ignorado se salvaron hasta `clean -fdx`. `rebase --abort` devolvió la rama a su commit original y con un cambio sin commit el rebase ni empezó. Tras `git gc` normal el commit perdido seguía; tras `reflog expire --expire=now` y `gc --prune=now` ya no estaba. No se probó la caducidad real de 30 y 90 días, ni restore, ni worktrees ni submódulos. Mismos resultados en 3 de 3 ejecuciones.
Este artículo no contiene enlaces de afiliado.
Cuando un git reset --hard o un git clean -fd sale mal, la pregunta es qué se puede traer de vuelta. La respuesta depende de si git llegó a guardar el contenido alguna vez, y eso no se ve a simple vista. Aquí se mide, caso por caso, con una marca de texto distinta en cada cambio, buscada después en todos los objetos del repositorio. Es el mismo enfoque de "qué se pierde" que ya se midió con git bundle: ahí se vio que los cambios sin commit y los ficheros sin seguimiento no viajan en la copia, y aquí se ve si se pueden recuperar. Si lo que quieres es que un commit no se llegue a hacer mal, mira el hook pre-commit y --no-verify. Para el mismo problema en el sistema de ficheros, está restaurar un fichero borrado desde rsnapshot, y para la copia que sí protege lo que git no guarda, restic en una copia 3-2-1 y restaurar una copia de seguridad como prueba.
Condiciones: Ubuntu 24.04.5 LTS, Linux 7.0.0-1017-oracle, git 2.43.0, LC_ALL=C.UTF-8, usuario normal (uid 10002), sin configuración global de git. Cada caso usa un repositorio nuevo creado con mktemp -d que el script borra al salir, con dos commits iniciales y ficheros de pocas líneas. "Recuperable" significa que la marca de texto sigue en algún objeto del repositorio (se recorren todos con git cat-file --batch-all-objects), no que sea cómodo recuperarla. El script se ejecutó 3 veces (cada una con 3 pasadas internas) y la salida fue idéntica en las 3; no se imprime ningún hash. No se probó git restore (solo checkout .), la caducidad real de las entradas del reflog (por defecto 90 días las alcanzables y 30 días las inalcanzables, aquí solo se fuerza con --expire=now), gc.pruneExpire con fechas antiguas, repositorios con objetos empaquetados de otros clientes, worktrees, submódulos, git reset --merge, ni recuperar con herramientas del editor o del sistema de ficheros (el historial local de un IDE o un fichero que aún siga abierto por un proceso). El texto lo redacté con ayuda de una IA a partir de la salida del script, y las cifras salen de esas ejecuciones.
Salida de la ejecución 1
Idéntica en las ejecuciones 2 y 3 (las tres pasadas internas de cada una también coinciden entre sí).
Ubuntu 24.04.5 LTS; Linux 7.0.0-1017-oracle; git version 2.43.0; uid=10002
=== run 1 ===
[1] git reset --hard HEAD~1 after a commit with a marker
file b.txt exists after reset: no; marker in objects: yes
reflog entries: 4; HEAD@{1} is the lost commit: yes
after git reset --hard HEAD@{1}: b.txt exists: yes; HEAD is the lost commit: yes
[2] git reset --hard with uncommitted changes (staged, unstaged, untracked)
s.txt (staged new file) exists: no; a.txt has unstaged marker: no; u.txt (untracked) exists: yes
marker in objects: staged yes; unstaged no; untracked no
reflog entries: 3; dangling blobs per git fsck: 1
content of the dangling blob: MARK_STAGED
files in .git/lost-found/other after fsck --lost-found: 1
[3] git checkout . with staged and unstaged changes in the same file
after checkout .: a.txt has staged marker: yes; unstaged marker: no; unstaged marker in objects: no
git status --short: [M a.txt ]
only unstaged: marker in file: no; in objects: no; untracked u.txt kept: yes
[4] git stash drop
after plain stash: u.txt (untracked) still in tree: yes; n.txt (staged new) in tree: no; stash entries: 1
after drop: stash entries: 0; stash commit still in objects: yes; marker in objects: yes
reflog of refs/stash exists: no
unreachable commits per fsck: 2
unreachable commit subject starts: WIP on
unreachable commit subject starts: index o
WIP commit found by fsck equals dropped stash: yes
git stash apply <hash>: a.txt has marker: yes; n.txt back: yes
git stash store: stash entries: 1
stash -u then drop: u.txt in tree: no; marker in objects: yes
apply <hash>: u.txt back: yes
[5] git clean -fd
u.txt exists: no; d/x.txt exists: no; st.txt (staged) exists: yes; i.log (ignored) exists: yes
marker in objects: untracked no; dir file no; staged yes
after clean -fdx: i.log exists: no
git clean -n lists: [Would remove u.txt ]; file still there: yes
[6] aborted rebase
rebase main (conflict) exit code: 1; in progress: yes; HEAD detached: yes
after --abort: branch: topic; HEAD equals original tip: yes
t2.txt exists: yes; status clean: yes
rebase with an uncommitted change: [error: cannot rebase: You have unstaged changes. error: Please commit or stash them. ]; marker still in file: yes
git reset --hard in the middle of a conflicted rebase:
rebase still in progress after reset --hard: yes; HEAD detached: yes
abort afterwards: HEAD equals original tip: yes
resolve a conflict by hand, then abort:
marker in file: no; marker in objects: yes; a.txt content: topic
completed rebase: HEAD changed: yes; ORIG_HEAD is old tip: yes; reflog mentions rebase: yes
reset --hard ORIG_HEAD: HEAD is old tip: yes
[7] how long the safety net lasts (lost commit after reset --hard)
plain git gc: commit still in objects: yes; reflog entry kept: yes
after reflog expire --expire=now: HEAD@{1} resolves to lost commit: no; commit in objects: yes
fsck still finds it unreachable: yes
Lo que se ve
- Commit perdido con
reset --hard. Trasgit reset --hard HEAD~1el fichero del commit desapareció del árbol, pero la marca seguía en los objetos yHEAD@{1}apuntaba al commit perdido.git reset --hard HEAD@{1}devolvió el fichero y dejó HEAD en ese commit. El reflog tenía 4 entradas en ese repositorio. - Cambios sin commit con
reset --hard. Con un fichero nuevo añadido congit add, un cambio sinadden un fichero seguido y un fichero sin seguimiento,reset --hardquitó los dos primeros y no tocó el tercero (u.txtsiguió ahí). El contenido del fichero conaddsiguió como 1 blob colgante:git fsck --no-reflogslo listó ygit cat-file -pmostróMARK_STAGED;git fsck --lost-founddejó 1 fichero en.git/lost-found/other. El cambio sinaddno estaba en ningún objeto, así que no hay nada que buscar. La razón es quegit addescribe el contenido en la base de objetos en ese momento y el cambio sinaddsolo existe en el árbol de trabajo. El reflog no ayuda con estos casos: tenía 3 entradas y ninguna refería a ese blob. git checkout .. Con un fichero que tenía una parte añadida conaddy otra sinadd,checkout .restauró desde el índice: la parte conaddquedó (git status --shortdioM a.txt, modificado y en el índice) y la parte sinadddesapareció sin estar en ningún objeto. Con un fichero solo modificado sinadd, tampoco quedó nada en los objetos, y el fichero sin seguimiento no se tocó.git stash drop. Ungit stashnormal dejó el fichero sin seguimiento en el árbol y quitó el nuevo conadd. Trasstash dropya no había entradas de stash y no habíastash@{0}, pero el commit seguía en el repositorio:git fsck --unreachable --no-reflogslistó 2 commits inalcanzables, uno que empieza porWIP ony otro porindex o(index on ...). El WIP era el stash borrado.git stash apply <hash>devolvió el cambio y el fichero conadd, ygit stash storelo volvió a registrar (1 entrada). Congit stash -u(que sí guarda lo no seguido), el fichero sin seguimiento salió del árbol, su marca siguió en los objetos tras eldropystash applylo devolvió. El orden en quefscklista los dos commits no es fijo, por lo que hay que mirar el asunto, no la posición.git clean -fd. Borró el fichero sin seguimiento y el del directorio nuevo; ninguna de las dos marcas estaba en los objetos. El fichero conaddsobrevivió (cleanno toca lo que está en el índice) y el ignorado (*.log) también hasta que se usó-fdx.git clean -ndlistó lo que borraría (Would remove u.txt) sin borrarlo, y es la única red que hay antes.- Rebase abortado. Con un conflicto,
git rebase mainsalió con código 1, dejó el rebase en curso y HEAD suelto.git rebase --abortdevolvió la ramatopical mismo commit de antes, con el fichero del segundo commit y el árbol limpio. Con un cambio sin commit el rebase ni empezó (cannot rebase: You have unstaged changes) y el cambio quedó intacto. Ungit reset --harden medio de un rebase con conflicto no lo cerró (seguía en curso y con HEAD suelto) y el--abortposterior también devolvió la rama a su commit. Si se resolvió un conflicto a mano y se hizoaddantes del--abort, el fichero volvió a la versión de la rama (topic) y la versión resuelta seguía como blob en los objetos. Tras un rebase completado,ORIG_HEADapuntaba al antiguo extremo de la rama ygit reset --hard ORIG_HEADlo devolvió. - Cuánto dura la red. Con el commit perdido tras
reset --hard, ungit gcnormal lo dejó en los objetos y con su entrada de reflog. Después degit reflog expire --expire=now --all,HEAD@{1}ya no apuntaba a él, aunque el commit seguía en los objetos yfsck --unreachableaún lo encontraba. Trasgit gc --prune=nowya no estaba el commit ni la marca en ningún objeto.
Qué significa
El reflog guarda cambios de punteros (a dónde apuntó HEAD y cada rama), no contenido: cubre lo que se llegó a commitear, también tras un reset --hard o un rebase. Lo que solo se había hecho con git add queda como blob colgante y se encuentra con fsck mientras no se purgue. Lo que ni se añadió ni se commiteó (un cambio en un fichero seguido, un fichero sin seguimiento) no existe para git, y checkout ., reset --hard y clean -fd no dejan copia: ahí solo ayuda una copia externa. En este caso concreto de repositorios mínimos, un git add o un git stash antes de la operación peligrosa fue lo que marcó la diferencia entre recuperable e irrecuperable. Las cifras (4 entradas de reflog, 1 blob colgante, 2 commits inalcanzables) son de estos repositorios de juguete y cambiarán en uno real; lo que se mantiene es qué categoría deja rastro y cuál no.
Script completo
#!/bin/bash
# What can be recovered after git reset --hard, checkout ., stash drop, clean -fd and an aborted rebase.
# Everything in throwaway repos under one mktemp -d dir, removed on exit. Real dates (so gc expiry ages are real); no hash is printed.
# "recoverable" is measured by searching every object in the repository (loose and packed) for a marker string.
# Usage: test-git-reset-hard-reflog-stash.sh
set -u
export LC_ALL=C.UTF-8
export GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_SYSTEM=/dev/null
export GIT_AUTHOR_NAME=t [email protected] GIT_COMMITTER_NAME=t [email protected]
T=$(mktemp -d /tmp/gitrec.XXXXXX) || exit 1
trap 'rm -rf "$T"' EXIT
echo "$(. /etc/os-release; echo "$PRETTY_NAME"); $(uname -sr); $(git --version); uid=$(id -u)"
yn(){ if "$@"; then echo yes; else echo no; fi; }
# in-object search: is the marker present in any object of the current repo?
inobj(){ git cat-file --batch-all-objects --batch-check='%(objectname)' | while read -r o; do git cat-file -p "$o" 2>/dev/null | grep -q "$1" && { echo yes; return; }; done | grep -q yes; }
newrepo(){ # $1 name; creates repo with 2 commits (c1: a.txt=base; c2: a.txt=base2)
R="$T/run$r-$1"; git init -q -b main "$R"; cd "$R" || exit 1
echo base > a.txt; git add a.txt; git commit -q -m c1
echo base2 > a.txt; git commit -q -am c2
}
for r in 1 2 3; do
echo "=== run $r ==="
echo "[1] git reset --hard HEAD~1 after a commit with a marker"
newrepo r1a; echo MARK_COMMITTED > b.txt; git add b.txt; git commit -q -m c3
h3=$(git rev-parse HEAD); git reset -q --hard HEAD~1
echo " file b.txt exists after reset: $(yn test -e b.txt); marker in objects: $(yn inobj MARK_COMMITTED)"
echo " reflog entries: $(git reflog | wc -l); HEAD@{1} is the lost commit: $(yn test "$(git rev-parse 'HEAD@{1}')" = "$h3")"
git reset -q --hard 'HEAD@{1}'; echo " after git reset --hard HEAD@{1}: b.txt exists: $(yn test -e b.txt); HEAD is the lost commit: $(yn test "$(git rev-parse HEAD)" = "$h3")"
echo "[2] git reset --hard with uncommitted changes (staged, unstaged, untracked)"
newrepo r2; echo MARK_STAGED > s.txt; git add s.txt
echo MARK_UNSTAGED >> a.txt
echo MARK_UNTRACKED > u.txt
git reset -q --hard
echo " s.txt (staged new file) exists: $(yn test -e s.txt); a.txt has unstaged marker: $(yn grep -q MARK_UNSTAGED a.txt); u.txt (untracked) exists: $(yn test -e u.txt)"
echo " marker in objects: staged $(yn inobj MARK_STAGED); unstaged $(yn inobj MARK_UNSTAGED); untracked $(yn inobj MARK_UNTRACKED)"
echo " reflog entries: $(git reflog | wc -l); dangling blobs per git fsck: $(git fsck --no-reflogs 2>/dev/null | grep -c '^dangling blob')"
b=$(git fsck --no-reflogs 2>/dev/null | awk '/^dangling blob/{print $3}' | head -1)
echo " content of the dangling blob: $(git cat-file -p "$b" 2>/dev/null)"
git fsck --lost-found >/dev/null 2>&1; echo " files in .git/lost-found/other after fsck --lost-found: $(ls .git/lost-found/other 2>/dev/null | wc -l)"
echo "[3] git checkout . with staged and unstaged changes in the same file"
newrepo r3; echo MARK_STAGED_PART >> a.txt; git add a.txt; echo MARK_UNSTAGED_PART >> a.txt
git checkout -q .
echo " after checkout .: a.txt has staged marker: $(yn grep -q MARK_STAGED_PART a.txt); unstaged marker: $(yn grep -q MARK_UNSTAGED_PART a.txt); unstaged marker in objects: $(yn inobj MARK_UNSTAGED_PART)"
echo " git status --short: [$(git status --short | tr '\n' ' ')]"
newrepo r3b; echo MARK_ONLY_UNSTAGED >> a.txt; echo MARK_UNTRACKED > u.txt; git checkout -q .
echo " only unstaged: marker in file: $(yn grep -q MARK_ONLY_UNSTAGED a.txt); in objects: $(yn inobj MARK_ONLY_UNSTAGED); untracked u.txt kept: $(yn test -e u.txt)"
echo "[4] git stash drop"
newrepo r4; echo MARK_STASHED >> a.txt; echo MARK_STASH_UNTRACKED > u.txt; echo MARK_STASH_TRACKEDNEW > n.txt; git add n.txt
git stash -q; echo " after plain stash: u.txt (untracked) still in tree: $(yn test -e u.txt); n.txt (staged new) in tree: $(yn test -e n.txt); stash entries: $(git stash list | wc -l)"
sh=$(git rev-parse 'stash@{0}'); git stash drop -q
echo " after drop: stash entries: $(git stash list | wc -l); stash commit still in objects: $(yn git cat-file -e "$sh"); marker in objects: $(yn inobj MARK_STASHED)"
echo " reflog of refs/stash exists: $(git rev-parse -q --verify 'stash@{0}' >/dev/null && echo yes || echo no)"
un=$(git fsck --unreachable --no-reflogs 2>/dev/null | grep -c '^unreachable commit'); echo " unreachable commits per fsck: $un"
c=""; for x in $(git fsck --unreachable --no-reflogs 2>/dev/null | awk '/^unreachable commit/{print $3}'); do echo "$(git log -1 --format=%s "$x" | cut -c1-7)" >> "$T/subj"; done; sort "$T/subj" | sed 's/^/ unreachable commit subject starts: /'; rm -f "$T/subj"
for x in $(git fsck --unreachable --no-reflogs 2>/dev/null | awk '/^unreachable commit/{print $3}'); do [ "$(git log -1 --format=%s "$x" | cut -c1-7)" = "WIP on " ] && c=$x; done
echo " WIP commit found by fsck equals dropped stash: $(yn test "$c" = "$sh")"
git stash apply -q "$c"; echo " git stash apply <hash>: a.txt has marker: $(yn grep -q MARK_STASHED a.txt); n.txt back: $(yn test -e n.txt)"
git stash store -q -m recovered "$c"; echo " git stash store: stash entries: $(git stash list | wc -l)"
newrepo r4b; echo MARK_UT > u.txt; git stash -q -u; sh=$(git rev-parse 'stash@{0}'); git stash drop -q
echo " stash -u then drop: u.txt in tree: $(yn test -e u.txt); marker in objects: $(yn inobj MARK_UT)"; git stash apply -q "$sh" >/dev/null 2>&1; echo " apply <hash>: u.txt back: $(yn test -e u.txt)"
echo "[5] git clean -fd"
newrepo r5; echo MARK_CLEAN_UNTRACKED > u.txt; mkdir d; echo MARK_CLEAN_DIR > d/x.txt; echo MARK_CLEAN_STAGED > st.txt; git add st.txt
echo '*.log' > .gitignore; git add .gitignore; git commit -q -m ign; echo MARK_IGNORED > i.log
git clean -fdq
echo " u.txt exists: $(yn test -e u.txt); d/x.txt exists: $(yn test -e d/x.txt); st.txt (staged) exists: $(yn test -e st.txt); i.log (ignored) exists: $(yn test -e i.log)"
echo " marker in objects: untracked $(yn inobj MARK_CLEAN_UNTRACKED); dir file $(yn inobj MARK_CLEAN_DIR); staged $(yn inobj MARK_CLEAN_STAGED)"
git clean -fdxq; echo " after clean -fdx: i.log exists: $(yn test -e i.log)"
newrepo r5b; echo MARK_DRY > u.txt; echo " git clean -n lists: [$(git clean -nd | tr '\n' ' ')]; file still there: $(yn test -e u.txt)"
echo "[6] aborted rebase"
newrepo r6; git checkout -q -b topic HEAD~1; echo topic > a.txt; git commit -q -am topic1; echo MARK_TOPIC2 > t2.txt; git add t2.txt; git commit -q -m topic2
before=$(git rev-parse HEAD); git rebase main >/dev/null 2>&1; rc=$?
echo " rebase main (conflict) exit code: $rc; in progress: $(yn test -d .git/rebase-merge); HEAD detached: $(yn test -z "$(git symbolic-ref -q HEAD)")"
git rebase --abort; echo " after --abort: branch: $(git symbolic-ref --short HEAD); HEAD equals original tip: $(yn test "$(git rev-parse HEAD)" = "$before")"
echo " t2.txt exists: $(yn test -e t2.txt); status clean: $(yn test -z "$(git status --short)")"
echo MARK_DIRTY >> t2.txt; out=$(git rebase main 2>&1 | head -2 | tr '\n' ' '); echo " rebase with an uncommitted change: [$out]; marker still in file: $(yn grep -q MARK_DIRTY t2.txt)"; git checkout -q .
git rebase main >/dev/null 2>&1; echo " git reset --hard in the middle of a conflicted rebase:"
git reset -q --hard; echo " rebase still in progress after reset --hard: $(yn test -d .git/rebase-merge); HEAD detached: $(yn test -z "$(git symbolic-ref -q HEAD)")"
git rebase --abort; echo " abort afterwards: HEAD equals original tip: $(yn test "$(git rev-parse HEAD)" = "$before")"
echo " resolve a conflict by hand, then abort:"
git rebase main >/dev/null 2>&1; echo MARK_RESOLVED > a.txt; git add a.txt; git rebase --abort
echo " marker in file: $(yn grep -q MARK_RESOLVED a.txt); marker in objects: $(yn inobj MARK_RESOLVED); a.txt content: $(cat a.txt)"
newrepo r6c; git checkout -q -b topic HEAD~1; echo t > t.txt; git add t.txt; git commit -q -m t1; old=$(git rev-parse HEAD)
git rebase -q main; echo " completed rebase: HEAD changed: $(yn test "$(git rev-parse HEAD)" != "$old"); ORIG_HEAD is old tip: $(yn test "$(git rev-parse ORIG_HEAD)" = "$old"); reflog mentions rebase: $(yn sh -c "git reflog | grep -q rebase")"
git reset -q --hard ORIG_HEAD; echo " reset --hard ORIG_HEAD: HEAD is old tip: $(yn test "$(git rev-parse HEAD)" = "$old")"
echo "[7] how long the safety net lasts (lost commit after reset --hard)"
newrepo r7; echo MARK_GC > g.txt; git add g.txt; git commit -q -m g; g=$(git rev-parse HEAD); git reset -q --hard HEAD~1
git gc -q; echo " plain git gc: commit still in objects: $(yn git cat-file -e "$g"); reflog entry kept: $(git rev-parse -q --verify 'HEAD@{1}' >/dev/null && echo yes || echo no)"
git reflog expire --expire=now --all; echo " after reflog expire --expire=now: HEAD@{1} resolves to lost commit: $(yn sh -c "test \"\$(git rev-parse -q --verify 'HEAD@{1}')\" = $g"); commit in objects: $(yn git cat-file -e "$g")"
echo " fsck still finds it unreachable: $(yn sh -c "git fsck --unreachable --no-reflogs 2>/dev/null | grep -q $g")"
git gc -q --prune=now; echo " after gc --prune=now: commit in objects: $(yn git cat-file -e "$g"); marker in objects: $(yn inobj MARK_GC)"
cd "$T"
done
Este artículo no contiene enlaces de afiliado.