DEV Community

Maulik Paghdal for Script Binary

Posted on • Originally published at scriptbinary.com

Undo Mistakes in Git: Revert, Reset, and Checkout Simplified

1. Git Revert

When to Use:

Use git revert to undo a specific commit while preserving your commit history. It’s ideal for public repositories where rewriting history can cause issues.

How It Works:

git revert creates a new commit that undoes the changes introduced by the targeted commit.

Example:

git revert <commit-hash>
Enter fullscreen mode Exit fullscreen mode

Git will prompt you to edit a commit message. Save it, and a new commit reversing the changes will be added.


2. Git Reset

When to Use:

Use git reset to undo changes by moving the HEAD pointer. This command is more destructive than revert as it alters commit history.

Modes of git reset:

  • --soft: Keeps changes in the staging area.
  • --mixed (default): Keeps changes in your working directory.
  • --hard: Discards changes completely.

Example:


# Reset to a specific commit and keep changes in working directory git reset --mixed <commit-hash> # Reset and discard changes git reset --hard <commit-hash>
Enter fullscreen mode Exit fullscreen mode

⚠️ Be cautious with --hard as it permanently deletes changes.


3. Git Checkout

When to Use:

Use git checkout to switch branches or restore files to a specific state.

Switching Branches:

git checkout <branch-name>
Enter fullscreen mode Exit fullscreen mode

Restoring Files:

Restore a specific file to the state of the last commit:

git checkout HEAD -- <file-name>
Enter fullscreen mode Exit fullscreen mode

When to Use What?

  • Revert: Undo a specific commit in a shared repository.
  • Reset: Rewrite commit history in local branches.
  • Checkout: Switch branches or restore files without modifying commits.

Best Practices

  1. Understand the Impact:
    • Use revert for safe, non-destructive changes.
    • Use reset only when working locally or with private branches.
  2. Always Backup:
    • Before using reset --hard, stash your changes or back up the branch.
  3. Collaborate:
    • For shared repositories, communicate with your team before altering history.

Conclusion

Knowing when and how to use revert, reset, and checkout can save you from hours of debugging and frustration. Git’s flexibility makes it an indispensable tool for developers.

Learn More

For a deeper dive and detailed examples, visit the original guide on Script Binary.


Let’s Discuss!

Have questions about Git commands? Share your thoughts in the comments below, and follow me for more Git and version control tips!

Top comments (0)