5 ways to undo a git commit

5 ways to undo a git commit

To undo a Git commit, there are several options, depending on the situation and the level of your code. Here are the common situations:

  1. Undo the Last Commit Without Changing Files

    There may be a situation whereby you want to undo the last commit but you want to keep your changes in your working directory. To do this, you can use git reset with the --soft option. This moves the branch pointer back to the last commit while keeping the changes staged (index):

    bash

    git reset --soft HEAD~1

    After running this command, you can make further changes and create a new commit.

  2. Undo the Last Commit and Unstage Changes

    You may want to undo the last commit and unstage your changes; you can do it using git reset with the --mixed option. This moves the branch pointer back to the last commit and unstages your changes:

    bash

    git reset --mixed HEAD~1

    This command will keep your changes in your working directory, and you can choose which changes to include in your next commit.

  3. Completely Discard the Last Commit and Changes

    If you want to completely discard the last commit and all changes associated with it, you can use git reset with the --hard option:

    bash

    git reset --hard HEAD~1

    This command will remove your last commit, and all your changes will go. When using it, use it with caution, as it's a destructive operation, and you won't be able to recover the changes.

  4. Undo Multiple Commits

    Let's say you need to undo multiple commits, you can specify a different number instead of 1 in the above examples, e.g., HEAD~2 to undo the last two commits.

  5. Undo a Commit and Create a New One

    If you want to undo a specific commit and create a new commit with different changes, you can use git revert. This creates a new commit that undoes the changes introduced by a previous commit:

    bash

    git revert <commit_sha>

    Replace <commit_sha> with the SHA-1 hash of the commit you want to undo. This is a safer way to undo changes as it doesn't rewrite history.

Push Changes to Remote:

After undoing commits, you might need to force push your changes to the remote repository if you've already pushed the commits you want to undo. Be cautious when force-pushing, as it can disrupt collaboration with others.
bash

git push origin <branch_name> --force

Remember to use these commands carefully, especially if you're working in a team, as they can affect the commit history that others are working on. Always consider discussing such changes with your team before force-pushing or making significant modifications to the commit history.