Copias de seguridad

Copia de un repositorio git con git bundle: crear, verificar, restaurar y qué se pierde

Publicado el 25 de noviembre de 2026Última revisión: 25 de noviembre de 202616 min de lectura

Resultado de la prueba

con un repositorio de 66 commits (.git de 500.016 bytes), git bundle create --all dio un fichero de 448.496 bytes (mediana 17 ms), git clone desde él funcionó con fsck limpio y las mismas puntas de rama, pero no trajo el stash, los hooks, la config local, el fichero sin seguimiento ni la edición sin commitear. cp -r .git conservó stash, hooks y config; git clone --mirror conservó el stash pero no hooks ni config. Un bundle incremental de 12 commits ocupó 3.697 bytes y no se pudo clonar solo. git bundle verify dio exit 0 con un byte alterado; el clon falló con exit 128.

Contenido

Este artículo no contiene enlaces de afiliado.

Un repositorio git en tu disco no es una copia de seguridad de nada, y copiar la carpeta a mano arrastra también basura y estado a medias. git bundle empaqueta el historial en un solo fichero que se guarda donde quieras y se clona después como si fuera un remoto. Se probó qué guarda, qué no, y cómo se compara con cp -r .git y git clone --mirror.

Condiciones: git 2.43.0 (salida de git --version), Linux arm64 con 2 CPU, disco local, GIT_CONFIG_GLOBAL y GIT_CONFIG_SYSTEM apuntando a /dev/null, identidad y fechas fijas. El repositorio se genera con Python random.Random(42): 60 commits en main sobre 30 ficheros de texto de nombre modNN.txt y 6 ficheros binarios aleatorios de 50.000 bytes, una etiqueta v1, una rama feature con 5 commits más y un commit final en main: 66 commits en total, 33 ficheros fuera de .git. Después se añadió lo que vive fuera del historial: un hook pre-commit, un stash, una edición sin commitear, un fichero sin seguimiento, un remote origin, y una clave de configuración local (backup.note). Tras git gc, .git pasó de 768.308 a unos 493.000 bytes, y con esos extras queda en 500.016. El script se ejecutó 3 veces enteras, cada una con 3 repeticiones de las medidas (9 en total); los tamaños cambian en unos pocos bytes entre ejecuciones (448.469, 448.496 y 448.498 el bundle) porque el commit del stash lleva la hora real. Cada ejecución sale con los mismos 66 commits y la misma punta de main (80fa194bb141). No se probó con repositorios grandes (decenas de MB o más), con submódulos, LFS, repositorios con historia en shallow, con git bundle sobre repositorios remotos, con git 2.x distintos de 2.43.0, con transferencia por red ni con cifrado del bundle; los tiempos son de un repo de medio megabyte y no extrapolan. Antes de la versión final del script se descartaron dos ejecuciones exploratorias: en la primera el stash salió vacío porque la edición caía en un fichero que no existía (quedó sin seguimiento, y no había nada que guardar), y la comprobación de que las ramas coincidían daba falso negativo por comparar también origin/HEAD. Ambos fallos eran del script, se corrigieron y esos números no aparecen aquí.

Crear, verificar y clonar

Con git bundle create copia.bundle --all en el repositorio de prueba (tiempos de 9 ejecuciones; ver el script para cada una):

Método Tamaño Tiempo (mediana de 3, ejecución 1)
git bundle create --all 448.496 bytes 17 ms
git bundle verify no escribe 3 ms
git clone copia.bundle n/a 49 ms
cp -r .git 500.016 bytes 5 ms
git clone --mirror 496.216 bytes 13 ms

git bundle verify no lo comprueba todo

Qué se pierde

Se restauró el repositorio con cada método y se miró qué había de lo que estaba fuera del historial:

Lo que existía en el original clone desde bundle clone --mirror cp -r .git (y checkout -f main)
Commits, ramas, etiquetas sí (feature como origin/feature) sí sí
Stash no (con fetch refs/*:refs/*, sí) sí sí
Hook pre-commit no no sí
backup.note (config local) no no sí
remote origin original no, apunta al .bundle no sí
Edición sin commitear en fichero con seguimiento no (0 coincidencias) no no: git status queda limpio tras el checkout -f
Fichero sin seguimiento (untracked.txt) no no no
Índice (cambios en staging) no no sí (el fichero index se copia)

Bundle incremental

Se hizo un bundle de main en el commit 66 (base.bundle, 438.169 bytes), se clonó, y se añadieron 12 commits a main. Después git bundle create inc.bundle BASE..main, con BASE el hash del commit 66:

Qué cambiar si lo usas

Script completo

#!/bin/bash
# git bundle as a repository backup: create, verify, clone, incremental, what is lost, vs cp -r .git and clone --mirror.
# Usage: test-git-bundle.sh WORKDIR [RUNS]
W=$1; RUNS=${2:-3}; [ -n "$W" ] || { echo "usage: $0 WORKDIR [RUNS]" >&2; exit 2; }
rm -rf "$W"; mkdir -p "$W"; W=$(cd "$W" && pwd)
export GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_SYSTEM=/dev/null GIT_TERMINAL_PROMPT=0
export GIT_AUTHOR_NAME=Test [email protected] GIT_COMMITTER_NAME=Test [email protected]
git --version; echo "cpus: $(nproc)"
now() { echo ${EPOCHREALTIME/./}; }
mk() { # build the throwaway repo in $1 (fixed seed, fixed dates -> same hashes every run)
python3 - "$1" <<'PY'
import random, sys, os, subprocess
r = random.Random(42); d = sys.argv[1]
words = ["def","return","import","class","self","value","config","backup","restore","server","for","in","if","else","None","True","error","path","file","index","data","count","print","while","try","except"]
os.makedirs(d); env = dict(os.environ)
def git(*a, **k):
    e = dict(env); e.update(k); subprocess.run(["git", "-C", d] + list(a), check=True, env=e, stdout=subprocess.DEVNULL)
git("init", "-q", "-b", "main")
git("config", "user.email", "[email protected]")   # repo-local config (not in any bundle)
git("config", "backup.note", "local setting")
n = 0
def commit(k):
    global n
    for _ in range(k):
        n += 1
        f = "%s/src/mod%02d.txt" % (d, r.randint(0, 29)); os.makedirs(os.path.dirname(f), exist_ok=True)
        with open(f, "a") as fh: fh.write("".join(" ".join(r.choice(words) for _ in range(8)) + "\n" for _ in range(200)))
        if n % 10 == 0: open("%s/blob%02d.bin" % (d, n // 10), "wb").write(r.randbytes(50000))
        git("add", "-A")
        date = "2026-01-01T00:%02d:%02d +0000" % (n // 60, n % 60)
        git("commit", "-q", "-m", "commit %d" % n, GIT_AUTHOR_DATE=date, GIT_COMMITTER_DATE=date)
commit(60)
git("tag", "v1"); git("branch", "feature")
git("checkout", "-q", "feature"); commit(5); git("checkout", "-q", "main")
commit(1)
PY
}
extras() { # things that live outside the commit graph, added after the commits
  cd "$1" || exit 1
  printf '#!/bin/sh\necho hook\n' > .git/hooks/pre-commit; chmod +x .git/hooks/pre-commit
  T=$(git ls-files src | head -1); echo "tracked change not committed" >> "$T"; git stash -q                # one stash
  echo "unstaged edit" >> "$T"                                             # uncommitted work
  echo "never added" > untracked.txt                                                  # untracked file
  git remote add origin https://example.invalid/repo.git                             # config: remote
}
facts() { # $1 = repo/git-dir given as -C path ; prints comparable facts
  local p=$1
  echo "refs=$(git -C "$p" for-each-ref | wc -l) heads=$(git -C "$p" for-each-ref refs/heads | wc -l) tags=$(git -C "$p" for-each-ref refs/tags | wc -l) stash=$(git -C "$p" rev-parse -q --verify refs/stash >/dev/null && echo yes || echo no)"
}
ms() { echo $(( ($2-$1)/1000 )); }

echo "== repository (python3 random.Random seed 42, fixed dates and identity)"
mk "$W/orig"; ORIG="$W/orig"
echo "commits (all refs): $(git -C "$ORIG" rev-list --all | wc -l), tip main: $(git -C "$ORIG" rev-parse --short=12 main)"
echo ".git size before extras: $(du -sb "$ORIG/.git" | cut -f1) bytes, after git gc: " | tr -d '\n'
git -C "$ORIG" gc -q; echo "$(du -sb "$ORIG/.git" | cut -f1) bytes"
(extras "$ORIG")
echo "working tree files (non-.git): $(cd "$ORIG" && find . -path ./.git -prune -o -type f -print | wc -l)"
echo "git status --short: $(git -C "$ORIG" status --short | tr '\n' '|')  stash entries: $(git -C "$ORIG" stash list | wc -l)"
echo "origin facts: $(facts "$ORIG")"
echo "origin .git: $(du -sb "$ORIG/.git" | cut -f1) bytes"
ALLREFS=$(git -C "$ORIG" for-each-ref --format='%(refname) %(objectname)' | sort | sha256sum | cut -c1-16)
echo "ref+hash digest of origin: $ALLREFS"

echo "== runs: create/verify/clone times and sizes (RUNS=$RUNS)"
for run in $(seq 1 "$RUNS"); do
  D="$W/run$run"; mkdir -p "$D"
  t0=$(now); git -C "$ORIG" bundle create "$D/full.bundle" --all >/dev/null 2>&1; t1=$(now)
  git bundle verify "$D/full.bundle" >/dev/null 2>&1; vexit=$?; t2=$(now)
  git clone -q "$D/full.bundle" "$D/fromb" 2>/dev/null; t3=$(now)
  t4=$(now); cp -r "$ORIG/.git" "$D/cpgit"; t5=$(now)
  git clone -q --mirror "$ORIG" "$D/mirror.git"; t6=$(now)
  git -C "$D/fromb" fsck --strict >/dev/null 2>&1; fs=$?
  # does the clone from bundle have the same branch tips?
  same=$(git -C "$D/fromb" for-each-ref --format='%(refname) %(objectname)' refs/remotes/origin | grep -v '^refs/remotes/origin/HEAD ' | sed 's#^refs/remotes/origin/##' | sort | sha256sum | cut -c1-8)
  want=$(git -C "$ORIG" for-each-ref --format='%(refname:short) %(objectname)' refs/heads | sort | sha256sum | cut -c1-8)
  [ "$same" = "$want" ] && tips=si || tips=NO
  echo "RUN $run bundle $(stat -c %s "$D/full.bundle") $(ms $t0 $t1) verify_exit=$vexit $(ms $t1 $t2) clone $(ms $t2 $t3) fsck=$fs tips=$tips cpgit $(du -sb "$D/cpgit" | cut -f1) $(ms $t4 $t5) mirror $(du -sb "$D/mirror.git" | cut -f1) $(ms $t5 $t6)" | tee -a "$W/runs.txt"
done
D="$W/run1"
echo "== bundle contents (run 1)"
git bundle list-heads "$D/full.bundle" | sed 's/^[0-9a-f]\{40\}/<hash>/'
echo "== what each method carries (run 1)"
echo "bundle --all, restored by git clone: $(facts "$D/fromb")  [clone of a bundle sees refs/heads as origin/*, tags as tags]"
git init -q --bare "$D/fb-bare"; git -C "$D/fb-bare" fetch -q "$D/full.bundle" 'refs/*:refs/*' 2>/dev/null
echo "bundle fetched with refs/*:refs/*: $(facts "$D/fb-bare")"
echo "clone --mirror: $(facts "$D/mirror.git")"
echo "cp -r .git: $(facts "$D/cpgit")"
echo "stash entries restored: bundle-fetch=$(git -C "$D/fb-bare" rev-parse -q --verify refs/stash >/dev/null && echo 1 || echo 0) mirror=$(git -C "$D/mirror.git" rev-parse -q --verify refs/stash >/dev/null && echo 1 || echo 0) cp-.git=$( [ -e "$D/cpgit/refs/stash" ] && echo 1 || echo 0)"
cp -r "$ORIG/.git" "$D/cpwork.git" 2>/dev/null
echo "-- working tree and config after restore"
for name in fromb; do
  echo "clone from bundle: untracked.txt $( [ -e "$D/$name/untracked.txt" ] && echo present || echo ausente ); uncommitted edit $(grep -c 'unstaged edit' "$D/$name/$(cd "$ORIG" && git ls-files src | head -1)") ; pre-commit hook $( [ -x "$D/$name/.git/hooks/pre-commit" ] && echo present || echo ausente ); backup.note=$(git -C "$D/$name" config backup.note || echo '(no existe)'); user.email=$(git -C "$D/$name" config user.email || echo '(no existe)'); remote origin url=$(git -C "$D/$name" remote get-url origin)"
done
git clone -q "$ORIG" "$D/plainclone"
echo "plain git clone of origin: untracked.txt $( [ -e "$D/plainclone/untracked.txt" ] && echo present || echo ausente ); hook $( [ -x "$D/plainclone/.git/hooks/pre-commit" ] && echo present || echo ausente ); backup.note=$(git -C "$D/plainclone" config backup.note || echo '(no existe)')"
git clone -q --mirror "$ORIG" "$D/m2.git"
echo "clone --mirror: hooks dir has pre-commit: $( [ -e "$D/m2.git/hooks/pre-commit" ] && echo si || echo no ); backup.note=$(git -C "$D/m2.git" config backup.note || echo '(no existe)'); remote.origin.mirror=$(git -C "$D/m2.git" config remote.origin.mirror)"
echo "cp -r .git: pre-commit $( [ -x "$D/cpgit/hooks/pre-commit" ] && echo si || echo no ); backup.note=$(git config -f "$D/cpgit/config" backup.note); stash in .git/refs: $( [ -e "$D/cpgit/refs/stash" ] && echo si || echo no ); index file (staged state) copied: $( [ -e "$D/cpgit/index" ] && echo si || echo no ); untracked.txt inside .git: no"
mkdir "$D/cpwt"; cp -r "$D/cpgit" "$D/cpwt/.git"; git -C "$D/cpwt" checkout -q -f main 2>/dev/null
echo "cp -r .git then 'git checkout -f main': untracked.txt $( [ -e "$D/cpwt/untracked.txt" ] && echo present || echo ausente ); stash entries: $(git -C "$D/cpwt" stash list | wc -l); git status --short after checkout: '$(git -C "$D/cpwt" status --short | tr '\n' '|')'"

echo "== verify failures"
git init -q "$W/empty"
echo "bundle verify on a corrupted bundle (1 byte XOR 0xFF at half):"
cp "$D/full.bundle" "$D/bad.bundle"
python3 - "$D/bad.bundle" <<'PY'
import sys
p = sys.argv[1]; b = bytearray(open(p, "rb").read()); b[len(b)//2] ^= 0xFF; open(p, "wb").write(b)
PY
git bundle verify "$D/bad.bundle" >"$W/vo" 2>&1; echo "  exit=$? $(tail -1 "$W/vo" | head -c 150)"
git clone -q "$D/bad.bundle" "$D/badclone" >"$W/vo" 2>&1; echo "  git clone of it: exit=$? $(tail -1 "$W/vo" | head -c 150)"
echo "bundle verify (good) outside any repository:"
(cd "$W" && git bundle verify "$D/full.bundle" >"$W/vo" 2>&1; echo "  exit=$? $(head -1 "$W/vo" | head -c 150)")
echo "bundle verify (good) inside an empty repo (--all bundle has no prerequisites):"
(cd "$W/empty" && git bundle verify "$D/full.bundle" >"$W/vo" 2>&1; echo "  exit=$? $(head -1 "$W/vo" | head -c 150)")

echo "== incremental bundle"
# base = state of main now; then 12 new commits on main in origin
BASE=$(git -C "$ORIG" rev-parse main)
git -C "$ORIG" bundle create "$W/base.bundle" main >/dev/null 2>&1
git clone -q -b main "$W/base.bundle" "$W/baseclone"
(cd "$ORIG"
 for i in $(seq 1 12); do echo "extra $i" >> src/mod02.txt; git add src/mod02.txt; date="2026-02-01T00:00:$(printf %02d $i) +0000"; GIT_AUTHOR_DATE=$date GIT_COMMITTER_DATE=$date git commit -q -n -m "inc $i" ; done)
git -C "$ORIG" bundle create "$W/inc.bundle" "$BASE..main" >/dev/null 2>&1
echo "full bundle of main now: $(git -C "$ORIG" bundle create "$W/fullmain.bundle" main >/dev/null 2>&1; stat -c %s "$W/fullmain.bundle") bytes; base bundle: $(stat -c %s "$W/base.bundle") bytes; incremental ($(git -C "$ORIG" rev-list --count $BASE..main) commits, range BASE..main): $(stat -c %s "$W/inc.bundle") bytes"
echo "prerequisite line in incremental bundle: $(sed -n '2,3p' "$W/inc.bundle" | head -c 200 | tr '\n' ' ' | sed 's/[0-9a-f]\{40\}/<hash>/g')"
(cd "$W/empty" && git bundle verify "$W/inc.bundle" >"$W/vo" 2>&1; echo "verify incremental in empty repo: exit=$? $(grep -m1 -i 'error\|prereq' "$W/vo" | sed 's/[0-9a-f]\{40\}/<hash>/g' | head -c 150)")
git clone -q "$W/inc.bundle" "$W/incclone" >"$W/vo" 2>&1; echo "git clone from incremental alone: exit=$? $(tail -1 "$W/vo" | head -c 150)"
(cd "$W/baseclone" && git bundle verify "$W/inc.bundle" >"$W/vo" 2>&1; echo "verify incremental inside base clone: exit=$? $(tail -1 "$W/vo" | head -c 100)"
 git pull -q "$W/inc.bundle" main >"$W/vo" 2>&1; echo "git pull from incremental in base clone: exit=$?; tip equals origin: $( [ "$(git rev-parse HEAD)" = "$(git -C "$ORIG" rev-parse main)" ] && echo si || echo NO ); commits: $(git rev-list --count HEAD)")

Este artículo no contiene enlaces de afiliado.