Useful git commands to recover commit mistakes

Useful git commands to recover commit mistakes

git diff, commit and reset

Play this article

Ignoring these small mistakes which seem to be "big" sometimes, leads a developer to procrastinate and postpone it for later and it may later lead to bugs and complications for large projects.

tenor.gif

#1 Compare your previous commit

Get this done in a single command instead of doing it manually

git diff --name-only HEAD HEAD~1

Use-cases:

  • To overlook an unknown error in any file
  • To quickly fix large file issues in the repository

#2 Don't add more commits for a simple thing

You don't need a separate commit for few lines of code or something silly, so it is a better practice to remove unnecessary commands and make a clean and developer-friendly repository.

git commit --amend --no-edit

Use-cases:

  • Old commit is replaced by a new commit (including ID)
  • Allows you to undo changes without creating a new commit message
  • To maintain a clean, presentable, and developer-friendly commit history

Additionally

  • If you want to add a new commit message:
git commit --amend -m “New commit message”

#3 Undo the last commit

Again, "sudden" mistakes!

git reset --soft HEAD~1

Use-cases:

  • Resets the code to the previous commit (to the 2nd last)
  • Remember, using soft lets your changes in the last preserved for later.

Additionally

  • If you want to permanently get rid of the last commit then use hard instead
git reset --hard HEAD~1