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>
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>
⚠️ Be cautious with
--hardas 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>
Restoring Files:
Restore a specific file to the state of the last commit:
git checkout HEAD -- <file-name>
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
- Understand the Impact:
- Use
revertfor safe, non-destructive changes. - Use
resetonly when working locally or with private branches.
- Use
- Always Backup:
- Before using
reset --hard, stash your changes or back up the branch.
- Before using
- 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)