Eliminar archivos de Git commit


Estoy usando Git y he enviado algunos archivos usando

git commit -a

Más tarde, descubrí que se había añadido un archivo a la confirmación por error.

¿Cómo puedo eliminar un archivo de la última confirmación?

 1134
Author: random, 2012-09-18

21 answers

Creo que otras respuestas aquí son erróneas, porque se trata de mover los archivos confirmados por error de nuevo al área de preparación de la confirmación anterior, sin cancelar los cambios realizados en ellos. Esto se puede hacer como Paritosh Singh sugirió:

git reset --soft HEAD^ 

O

git reset --soft HEAD~1

Luego restablece los archivos no deseados para dejarlos fuera de la confirmación:

git reset HEAD path/to/unwanted_file

Ahora vuelve a confirmar, incluso puedes reutilizar el mismo mensaje de confirmación:

git commit -c ORIG_HEAD  
 2196
Author: juzzlin,
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-01-04 09:36:14

ATENCIÓN! Si solo desea eliminar un archivo de su confirmación anterior, y mantenerlo en el disco, lea la respuesta de juzzlin justo arriba.

Si esta es su última confirmación y desea eliminar completamente el archivo de su repositorio local y remoto , puede:

  1. eliminar el archivo git rm <file>
  2. confirmar con el indicador amend: git commit --amend

El indicador amend le dice a git que confirme de nuevo, pero "merge" (no en el sentido de fusionar dos ramas) este commit con el último commit.

Como se indica en los comentarios, usar git rm aquí es como usar el propio comando rm!

 228
Author: CharlesB,
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-02-06 03:19:55

Las respuestas existentes están hablando de eliminar los archivos no deseados de la último comprométete.

Si desea eliminar archivos no deseados de un viejo commit (incluso empujado) y no quieren crear un nuevo commit, que es innecesario, debido a la acción:

1.

Encuentre la confirmación a la que desea que se ajuste el archivo.

git checkout <commit_id> <path_to_file>

Puede hacer esto varias veces si desea eliminar muchos file.

2.

git commit -am "remove unwanted files"

3.

Encuentra el commit_id de la confirmación en la que se agregaron los archivos por error, digamos" 35c23c2 " aquí

git rebase 35c23c2~1 -i  // notice: "~1" is necessary

Este comando abre el editor de acuerdo a su configuración. El predeterminado es vim.

Mueva la última confirmación, que debería ser "eliminar archivos no deseados", a la siguiente línea de la confirmación incorrecta("35c23c2" en nuestro caso), y establezca el comando como fixup:

pick 35c23c2 the first commit
fixup 0d78b28 remove unwanted files

Usted debe ser bueno después de salvar la file.

Para terminar:

git push -f

Si desafortunadamente tienes conflictos, tienes que resolverlos manualmente.

 111
Author: Brian,
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-10-28 11:40:57

Como indica la respuesta aceptada, puede hacer esto restableciendo toda la confirmación. Pero este es un enfoque bastante pesado.
Una forma más limpia de hacer esto sería mantener la confirmación, y simplemente eliminar los archivos modificados de ella.

git reset HEAD^ -- path/to/file
git commit --amend --no-edit

El git reset tomará el archivo como estaba en el commit anterior, y lo colocará en el índice. El archivo en el directorio de trabajo está intacto.
El git commit entonces confirmará y aplastará el índice en la confirmación actual.

Esto esencialmente toma la versión del archivo que estaba en la confirmación anterior y la agrega a la confirmación actual. Esto resulta en ningún cambio neto, por lo que el archivo se elimina efectivamente de la confirmación.

 72
Author: Patrick,
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-27 05:58:07

Si no ha empujado los cambios en el servidor puede utilizar

git reset --soft HEAD~1

Restablecerá todos los cambios y revertirá a una confirmación

Si ha empujado sus cambios, siga los pasos que respondió @CharlesB

 35
Author: Paritosh Singh,
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-09-18 18:40:43

Eliminando el archivo usando rm lo eliminará!

Siempre estás agregando a un commit en git en lugar de eliminar, por lo que en este caso devuelve el archivo al estado en el que estaba antes del primer commit (esto puede ser una acción eliminar 'rm' si el archivo es nuevo) y luego vuelve a commit y el archivo irá.

Para devolver el archivo a algún estado anterior:

    git checkout <commit_id> <path_to_file>

O para devolverlo al estado en la CABEZA remota:

    git checkout origin/master <path_to_file>

Entonces modifique la confirmación y debería encontrar que el archivo tiene desaparecido de la lista(y no eliminado de su disco!)

 34
Author: Bob Flannigon,
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
2013-01-28 14:00:04
git checkout HEAD~ path/to/file
git commit --amend
 33
Author: Denis Shchepetov,
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
2013-08-23 19:01:20

Lo siguiente eliminará el archivo deseado, que es lo que pidió el OP.

git reset HEAD^ /path/to/file

Verás algo como lo siguiente...

Cambios a confirmar: (use " git reset HEAD..."a unstage)

Modificado:/ruta/al / archivo

Cambios no preparados para la confirmación: (use " git add..." actualizar lo que se confirmará) (use " git checkout git ..." descartar cambios en el directorio de trabajo)

Modificado: / path/to / file

  • "Changes to be committed" es la versión anterior del archivo antes de la confirmación. Esto se verá como una eliminación si el archivo nunca existió. Si confirma este cambio, habrá una revisión que revierte el cambio al archivo en su rama.
  • "Changes not staged for commit" es el cambio que ha confirmado, y el estado actual del archivo

En este punto, puede hacer lo que quiera con el archivo, como restablecer a un versión diferente.

Cuando estés listo para comprometer:

git commit --amend -a

O (si tienes otros cambios que no quieres confirmar, todavía)

git commit add /path/to/file
git commit --amend
 28
Author: ThatsAMorais,
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-12-07 07:13:42

Si desea conservar su commit (tal vez ya pasó algún tiempo escribiendo un mensaje de commit detallado y no desea perderlo), y solo desea eliminar el archivo de la confirmación, pero no del repositorio por completo:

git checkout origin/<remote-branch> <filename>
git commit --amend
 9
Author: mattexx,
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
2013-06-17 20:07:30

Les explicaré con el ejemplo.
Sea A, B, C 3 confirmaciones sucesivas. Commit B contiene un archivo que no debería haber sido confirmado.

git log  # take A commit_id
git rebase -i "A_commit_ID" # do an interactive rebase
change commit to 'e' in rebase vim # means commit will be edited
git rm unwanted_file
git rebase --continue
git push --force <branchName>   
 9
Author: Moaz Rashad,
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-06 11:16:40

El uso de git GUI puede simplificar la eliminación de un archivo de la confirmación anterior.

Asumiendo que esto no es una rama compartida y no te importa reescribir el historial , entonces ejecuta:

git gui citool --amend

Puede anular la comprobación del archivo que se cometió por error y luego hacer clic en "Confirmar".

introduzca la descripción de la imagen aquí

El archivo se elimina de la confirmación, pero será mantenido en el disco. Así que si desmarcó el archivo después de agregarlo por error, se mostrará en su lista de archivos no rastreados (y si desmarcado el archivo después de modificarlo por error, se mostrará en su lista de cambios no preparados para confirmación).

 8
Author: JDiMatteo,
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-05-20 15:56:07
git rm --cached <file_to_remove_from_commit_<commit_id>_which_added_file>
git commit -m "removed unwanted file from git"

Le dejará el archivo local todavía. Si tampoco desea el archivo localmente, puede omitir la opción c cached.

Si todo el trabajo está en su rama local, necesita mantener el archivo en una confirmación posterior, y al igual que tener un historial limpio, creo que una forma más simple de hacer esto podría ser:

git rm --cached <file_to_remove_from_commit_<commit_id>_which_added_file>
git commit --squash <commit_id>
git add <file_to_remove_from_commit_<commit_id>_which_added_file>
git commit -m "brand new file!"
git rebase --interactive <commit_id>^

Y luego puede terminar el rebase con facilidad sin tener que recordar comandos más complejos o enviar mensajes o escribir tanto.

 8
Author: Bryan Buckley,
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-23 06:28:27

Haga una secuencia de los siguientes comandos:

//to remove the last commit, but preserve changes  
git reset --soft HEAD~1

//to remove unneded file from the staging area  
git reset HEAD `<your file>` 

//finally make a new commit  
git commit -m 'Your message'
 5
Author: Sergey Onishchenko,
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-08-17 01:16:48

Solo quería complementar la respuesta superior ya que tuve que ejecutar un comando adicional:

git reset --soft HEAD^
git checkout origin/master <filepath>

Salud!

 4
Author: andrepo,
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-05-25 15:24:40

Algo que funcionó para mí, pero aún así creo que debería haber una mejor solución:

$ git revert <commit_id>
$ git reset HEAD~1 --hard

Simplemente deje el cambio que desea descartar en el otro commit, revise otros

$ git commit --amend // or stash and rebase to <commit_id> to amend changes
 3
Author: saiyancoder,
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-08-14 05:34:23

git reset --soft HEAD^ devuelve tu commit, y cuando escribes git status, te dice qué hacer:

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)
 3
Author: cardamom,
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-05-08 08:40:30

En realidad, creo que una forma más rápida y fácil es usar el modo interactivo git rebase.

git rebase -i head~1  

(o cabeza~4, hasta donde quieras llegar)

Y luego, en lugar de 'pick', use 'edit'. No me di cuenta de lo poderoso que es 'editar'.

Https://www.youtube.com/watch?v=2dQosJaLN18

Espero que lo encuentres útil.

 2
Author: Matt,
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-08-16 16:50:19

Tuvo el mismo problema cuando tengo cambios en una rama local donde quería revertir solo un archivo. Lo que funcionó para mí fue -

(feature / target_branch a continuación es donde tengo todos mis cambios, incluidos los que quería deshacer para un archivo específico)

(origin / feature / target_branch es la rama remota a la que quiero enviar mis cambios)

(feature / staging es mi rama temporal de staging desde la que estaré empujando todos mis cambios deseados excluyendo el cambio a ese archivo)

  1. Crear una rama local desde mi origin / feature / target_branch - llamada feature / staging

  2. Fusionado mi rama local de trabajo feature / target_branch a la rama feature/staging

  3. Checked out feature / staging luego git reset soft soft ORIG_HEAD (Ahora todos los cambios de la función / puesta en escena ' se organizarán, pero no comprometido.)

  4. Unstaged el archivo que he comprobado previamente con cambios innecesarios

  5. Se ha cambiado la rama ascendente de feature / staging a origin / feature / target_branch

  6. Se ha confirmado el resto de los cambios por etapas y se ha enviado el upstream a mi control remoto origin / feature / target_branch

 2
Author: user1201303,
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 05:03:08

Si ya no necesita ese archivo, puede hacer

git rm file
git commit --amend
git push origin branch
 1
Author: tven,
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-09-28 21:49:21

Si estás usando GitHub y aún no has enviado la confirmación, GitHub Desktop resuelve este problema fácilmente:

  1. Elija Repositorio - > Deshacer Confirmación más reciente
  2. Deselecciona el archivo que agregaste por error. Su mensaje de confirmación anterior ya estará en el cuadro de diálogo.
  3. Pulse el botón Commit!
 0
Author: Ron,
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-26 14:32:50

Esto funciona para mí para eliminar el archivo del repositorio del cubo de bits que empujé el archivo a la rama inicialmente.

git checkout origin/develop <path-to-file>
git add <path-to-file>
git commit -m "Message"
git push
 0
Author: swathi,
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-08-14 16:19:26