How to undo a commit in Git?
There are three ways to undo a commit depending on the situation.
If the commit has not been pushed to a shared repository yet, use git reset. The command git reset --soft HEAD~1 undoes the last commit but keeps changes in the staging area — you can edit the message and commit again. The command git reset --mixed HEAD~1 (the default behavior) undoes the commit and removes changes from the index, but keeps them in the working directory. The command git reset --hard HEAD~1 completely removes both the commit and the changes — use it only if you are absolutely sure the code is not needed.
If the commit has already been pushed to a shared repository, use git revert. The command git revert HEAD creates a new commit that undoes the changes of the previous one. This is safe for team collaboration because history is not rewritten — a new undo commit is added. You can revert multiple commits: git revert HEAD~3..HEAD.
If you only need to change the last commit's message or add a forgotten file, use git commit --amend. This command replaces the last commit with a new one with the same content but a different message or additional files. Do not use --amend for commits that have already been pushed — it rewrites history and creates problems for other developers.
Rule: reset — for local commits, revert — for shared, amend — for fixing the last commit before push.