¿Deshacer las modificaciones de la copia de trabajo de un archivo en Git?


Después de la última confirmación, modificé un montón de archivos en mi copia de trabajo, pero quiero deshacer los cambios en uno de esos archivos, como en restablecer al mismo estado que la confirmación más reciente.

Sin embargo, solo quiero deshacer los cambios de la copia de trabajo de solo ese archivo, nada más con él.

¿Cómo hago eso?

Author: S H, 2009-03-28

12 answers

Puede usar

git checkout -- file

Puede hacerlo sin el -- (como sugiere nimrodm), pero si el nombre del archivo se parece a una rama o etiqueta (u otro identificador de revisión), puede confundirse, por lo que usar -- es mejor.

También puede consultar una versión particular de un archivo:

git checkout v1.2.3 -- file         # tag v1.2.3
git checkout stable -- file         # stable branch
git checkout origin/master -- file  # upstream master
git checkout HEAD -- file           # the version from the most recent commit
git checkout HEAD^ -- file          # the version before the most recent commit
 1841
Author: Brian Campbell,
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
2014-05-30 02:30:59
git checkout <commit> <filename>

Usé esto hoy porque me di cuenta de que mi favicon había sido sobrescrito hace unos pocos commits cuando cambié a drupal 6.10, así que tuve que recuperarlo. Esto es lo que hice:

git checkout 088ecd favicon.ico
 118
Author: neoneye,
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
2009-03-28 10:25:25

Solo use

git checkout filename

Esto reemplazará filename con la última versión de la rama actual.

ADVERTENCIA: sus cambios serán descartados - no se mantiene ninguna copia de seguridad.

 103
Author: nimrodm,
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
2014-05-30 02:32:10

Si su archivo ya está preparado (sucede cuando hace un git add, etc. después de que se edite el archivo) para eliminar la etapa de sus cambios.

Use

git reset HEAD <file>

Entonces

git checkout <file>

Si aún no está preparado, simplemente use

git checkout <file>
 52
Author: thanikkal,
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-03-31 07:08:00

Si desea deshacer los cambios de la confirmación anterior en ese archivo, puede probar esto:

git checkout branchname^ filename

Esto comprobará el archivo como estaba antes de la última confirmación. Si desea volver a realizar algunas confirmaciones más, use la notación branchname~n.

 15
Author: sykora,
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
2014-05-30 02:32:42

Siempre me confundo con esto, así que aquí hay un caso de prueba recordatorio; digamos que tenemos este bash script para probar git:

set -x
rm -rf test
mkdir test
cd test
git init
git config user.name test
git config user.email [email protected]
echo 1 > a.txt
echo 1 > b.txt
git add *
git commit -m "initial commit"
echo 2 >> b.txt
git add b.txt
git commit -m "second commit"
echo 3 >> b.txt

En este punto, el cambio no se realiza en la caché, por lo que git status es:

$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   b.txt

no changes added to commit (use "git add" and/or "git commit -a")

Si desde este punto hacemos git checkout, el resultado es este:

$ git checkout HEAD -- b.txt
$ git status
On branch master
nothing to commit, working directory clean

Si en cambio hacemos git reset, el resultado es:

$ git reset HEAD -- b.txt
Unstaged changes after reset:
M   b.txt
$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   b.txt

no changes added to commit (use "git add" and/or "git commit -a")

Así que, en este caso - si los cambios no están preparados, git reset no hace ninguna diferencia, mientras que git checkout sobrescribe la cambio.


Ahora, digamos que el último cambio del script anterior es staged/cached, es decir, también lo hicimos git add b.txt al final.

En este caso, git status en este punto es:

$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    modified:   b.txt

Si desde este punto hacemos git checkout, el resultado es este:

$ git checkout HEAD -- b.txt
$ git status
On branch master
nothing to commit, working directory clean

Si en cambio hacemos git reset, el resultado es:

$ git reset HEAD -- b.txt
Unstaged changes after reset:
M   b.txt
$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   b.txt

no changes added to commit (use "git add" and/or "git commit -a")

Entonces, en este caso - si los cambios son por etapas, git reset básicamente hará cambios por etapas en cambios no escalonados - mientras que git checkout sobrescribirá los cambios completamente.

 7
Author: sdaau,
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-02-09 08:56:33

Restauro mis archivos usando el SHA id, lo que hago es git checkout <sha hash id> <file name>

 5
Author: Beto,
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-05-22 20:39:17

Lo he hecho a través de git bash:

(use "git checkout -- <file>..." to discard changes in working directory)

  1. Estado de Git. [Así que hemos visto un archivo wad modificado.]
  2. git checkout index index.html [he cambiado en el índice.archivo html:
  3. git status [ahora esos cambios fueron eliminados]

introduzca la descripción de la imagen aquí

 5
Author: Shivanandam Sirmarigari,
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
2018-04-12 13:04:25

Esta respuesta es para el comando necesario para deshacer cambios locales que están en varios archivos específicos en la misma o varias carpetas(o directorios). Esta respuesta aborda específicamente la pregunta donde un usuario tiene más de un archivo pero el usuario no quiere deshacer todos los cambios locales:

Si tiene uno o más archivos, podría aplicar el comando samne (git checkout -- file) a cada uno de esos archivos enumerando cada una de sus ubicaciones separadas por espacio como en:

git checkout -- name1/name2/fileOne.ext nameA/subFolder/fileTwo.ext

Tenga en cuenta el espacio abve entre name1/name2/fileOne.nombre ext A / Subcarpeta / fileTwo.ext

Para varios archivos en la misma carpeta:

Si necesita descartar cambios para todos los archivos en un cierto directorio, utilice el git checkout de la siguiente manera:

git checkout -- name1/name2/*

El asterisco en el anterior hace el truco de deshacer todos los archivos en esa ubicación bajo name1/name2.

Y, de manera similar, lo siguiente puede deshacer los cambios en todos los archivos para multiple carpetas:

git checkout -- name1/name2/* nameA/subFolder/*

Otra vez tenga en cuenta el espacio entre name1 / name2/ * nameA / subcarpeta / * en el arriba.

Nota: name1, name2, nameA, subcarpeta: todos estos nombres de carpeta de ejemplo indican la carpeta o paquete donde pueden residir los archivos en cuestión.

 3
Author: Nirmal,
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-01-23 21:26:27

Si aún no has enviado o compartido tu confirmación:

git diff --stat HEAD^...HEAD | \
fgrep filename_snippet_to_revert | cut -d' ' -f2 | xargs git checkout HEAD^ --
git commit -a --amend
 2
Author: Jesse Glick,
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
2014-05-30 02:28:41

Para mí solo este funcionó

git checkout -p filename

introduzca la descripción de la imagen aquí

 1
Author: Ramesh Bhupathi,
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-08-19 14:28:04

Si ya está confirmado, puede revertir el cambio para el archivo y confirmar de nuevo, luego aplastar la nueva confirmación con la última confirmación.

 0
Author: Gina,
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-04-26 19:17:07