¿Cómo puedes deshacer el último git add?


¿Es posible eliminar el último cambio de staged (no confirmado) en git? Supongamos que hay muchos archivos en la rama actual, algunos preparados, otros no. En algún momento, algún programador tonto ejecutó accidentalmente:

git add -- .

...en lugar de:

git checkout -- .

¿Puede este programador ahora deshacer sus últimos cambios con algún comando mágico git? ¿O debería haberse comprometido antes de experimentar en primer lugar?

 172
git
Author: Septagram, 2012-08-26

8 answers

Puede usar git reset. Esto 'borrará' todos los archivos que haya agregado después de su última confirmación.

Si desea eliminar el formato de algunos archivos, utilice git reset -- <file 1> <file 2> <file n>.

También es posible eliminar algunos de los cambios en los archivos utilizando git reset -p.

 281
Author: thameera,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-26 17:59:35

No puedes deshacer el último git add, pero puedes deshacer todos los adds desde la última confirmación. git reset sin un argumento de confirmación se restablece el índice (unstages staged changes):

git reset
 37
Author: knittl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-26 18:21:52

Así que la verdadera respuesta a

¿Puede este programador ahora deshacer sus últimos cambios con algún comando mágico de git?

Es en realidad: No, no se puede desapasionar solo el último git add.

Eso es si interpretamos la pregunta como en la siguiente situación:

Archivo inicial:

void foo() {

}

main() {
    foo();
}

Primer cambio seguido de git add:

void foo(int bar) {
    print("$bar");
}

main() {
    foo(1337);
}

Segundo cambio seguido de git add:

void foo(int bar, String baz) {
    print("$bar $baz");
}

main() {
    foo(1337, "h4x0r");
}

En este caso, git reset -p no ayudará, ya que su la granularidad más pequeña son las líneas. git no sabe eso sobre el estado intermedio de:

void foo(int bar) {
    print("$bar");
}

main() {
    foo(1337);
}

Más.

 15
Author: stanm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-17 12:35:38

Puedes usar git reset (ver docs )

 5
Author: davids,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-26 17:39:32

En la fecha git pide:

  1. use "git rm --cached <file>..." to unstage si los archivos no estaban en el repositorio. Deshace los archivos manteniéndolos allí.
  2. use "git reset HEAD <file>..." to unstage si los archivos estaban en el repositorio, y los está agregando como modificados. Mantiene los archivos tal y como están, y no los almacena.

Que yo sepa, no se puede deshacer el git add -- pero se puede deshacer una lista de archivos como se mencionó anteriormente.

 2
Author: theGiallo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-06 20:25:59
  • Elimine el archivo del índice, pero manténgalo versionado y con los cambios no confirmados en la copia de trabajo:

    git reset head <file>
    
  • Restablezca el archivo al último estado desde HEAD, deshaciendo los cambios y eliminándolos del índice:

    git reset HEAD <file>
    git checkout <file>
    
    # If you have a `<branch>` named like `<file>`, use:
    git checkout -- <file>
    

    Esto es necesario ya que git reset --hard HEAD no funcionará con archivos individuales.

  • Remove <file> from index and versioning, keeping the un-versioned file with changes in working copy:

    git rm --cached <file>
    
  • Eliminar <file> de copia de trabajo y versionado completo:

    git rm <file>
    
 2
Author: Faisal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-04 05:29:16

Si quieres eliminar todos los archivos agregados de git para confirmar

git reset

Si desea eliminar un archivo

git rm <file>
 1
Author: BSB,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-25 11:03:57

Dependiendo del tamaño y la escala de la dificultad, puede crear una rama scratch (temporal) y confirmar el trabajo actual allí.

Luego cambia a tu rama original, y elige los archivos apropiados de la confirmación de scratch.

Al menos tendría un registro permanente de los estados actuales y anteriores para trabajar (hasta que elimine esa rama de scratch).

 0
Author: Philip Oakley,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-27 13:06:33