Git
Undo a commit & redo
$ git commit -m "Something terribly misguided" # (0: Your Accident)
$ git reset HEAD~ # (1)
[ edit files as necessary ] # (2)
$ git add . # (3)
$ git commit -c ORIG_HEAD # (4)git resetis the command responsible for the undo. It will undo your last commit while leaving your working tree (the state of your files on disk) untouched. You’ll need to add them again before you can commit them again.- Make corrections to working tree files.
git addanything that you want to include in your new commit.- Commit the changes, reusing the old commit message.
resetcopied the old head to.git/ORIG_HEAD;commitwith-c ORIG_HEADwill open an editor, which initially contains the log message from the old commit and allows you to edit it. If you do not need to edit the message, you could use the-Coption.
Alternatively, to edit the previous commit (or just its commit message), commit --amend will add changes within the current index to the previous commit.
To remove (not revert) a commit that has been pushed to the server, rewriting history with git push origin main --force[-with-lease] is necessary. It’s almost always a bad idea to use --force; prefer --force-with-lease instead, and as noted in the git manual:
Cómo deshacer el último commit
Si no has hecho push:
- Para mantener cambios:
git reset --soft HEAD~1 - Para eliminar cambios:
git reset --hard HEAD~1 - Para arreglar el commit (mensaje o añadir cambios):
git commit --amend -m "Mensaje corregido"
Ya has hecho push:
git revert <hash>para crear un nuevo commit que invierte los cambios. Si hay conflictos, prepárate para manejarlos.git logpara recuperar el hash del commit que quieres revertir.
Nivel experto:
git rebase -ipara modificar tu historial de commits localmente. Puedes cambiar el orden, combinar, editar o eliminar commits.- Luego ejecuta
git push --force-with-lease - ⚠️ Aviso: Sólo usa rebase y push forzado en ramas donde seas el único colaborador o en situaciones donde todos los colaboradores estén al tanto y de acuerdo con reescribir la historia.