The goal of this tutorial is to provide a comprehensive guide on how to undo changes and reset commits in Git. This will empower you to revert your code to a previous state with ease and precision.
By the end of this tutorial, you will learn:
git stash
, git checkout
, git reset
, git revert
)Basic knowledge of Git and familiarity with the command line are recommended. If you haven't yet installed Git, you can follow the instructions here.
Git offers several commands for undoing changes. They each serve different purposes, and it's important to understand which to use in different scenarios.
git stash
: Temporarily saves changes that you don't want to commit immediately.git checkout
: Discards changes in the working directory.git reset
: Unstages changes, or optionally discards them.git revert
: Undoes a committed snapshot.git stash
# Make some changes in your working directory
echo "Temporary changes" > temp.txt
# Stash changes
git stash
# Shows the list of stashes
git stash list
In the code above, we first make some temporary changes. We then use git stash
to save these changes. git stash list
shows all the stashed changes.
git checkout
# Make some changes in your working directory
echo "Unwanted changes" > unwanted.txt
# Discard changes in the working directory
git checkout -- unwanted.txt
In this example, we make some unwanted changes and then use git checkout
to discard them.
git reset
# Make some changes and stage them
echo "Bad changes" > bad.txt
git add bad.txt
# Unstage changes
git reset
# Discard changes
git reset --hard
In this code, we first stage some changes. We then use git reset
to unstage them, and git reset --hard
to discard them completely.
git revert
# Commit some changes
echo "Wrong commit" > wrong.txt
git add wrong.txt
git commit -m "Wrong commit"
# Revert the last commit
git revert HEAD
In this example, we commit some changes and then use git revert
to create a new commit that undoes those changes.
In this tutorial, we learned about undoing changes and resetting commits in Git. We explored the git stash
, git checkout
, git reset
, and git revert
commands, and learned when to use each one.
Exercise: Create a new file, add some content, and then stash your changes.
Solution: echo "Some content" > file.txt ; git stash
Exercise: Add some content to a file, stage the changes, and then unstage them.
Solution: echo "More content" >> file.txt ; git add file.txt ; git reset
Exercise: Commit some changes, and then create a new commit that undoes those changes.
Solution: echo "Bad commit" >> file.txt ; git add file.txt ; git commit -m "Bad commit" ; git revert HEAD
Continue practicing these commands until you feel comfortable with them. Remember, the key to mastering Git (or any other tool) is consistent practice. Happy coding!