Welcome to our deep dive into the Git command git reset --hard! In this lesson, we'll learn what git reset --hard does, why it's useful, and how to use it correctly. Let's get started!
git reset --hard is a Git command that moves the current HEAD to a specific commit, discarding all changes made since the commit. It's a powerful tool that allows you to go back in time within your project's history.
You might use git reset --hard in situations like:
Before we start, ensure you have the following:
git init, git add, and git commitTo make this lesson practical, we'll be working with a simple example project: a directory containing a README.md file with some content.
mkdir my-project
cd my-project
echo "# My Project" > README.md
git init
touch file1.txt
git add .
git commit -m "Initial commit"Now, let's create a new commit with changes we don't want:
echo "Unwanted changes" >> README.md
git add .
git commit -m "Add unwanted changes"You can see the change by running git log:
commit 5e6198d510f9c410b4279d3c541f21f95a400b44 (HEAD -> main)
Author: You <you@example.com>
Date: Thu Mar 10 10:00:00 2022 -0700
Add unwanted changes
commit 2f8a8e65b56b466e781183a24a2f50478376143d (origin/main, origin/HEAD)
Author: You <you@example.com>
Date: Thu Mar 10 09:00:00 2022 -0700
Initial commitTo move back to the previous commit using git reset --hard, run:
git reset --hard HEAD^Now, if you check the content of README.md, you'll notice it has reverted to its previous state.
What does `git reset --hard` do?
While git reset --hard can be a lifesaver in certain situations, it's essential to use it with caution. Remember, once you use git reset --hard, all local changes will be lost.
We've learned about Git's git reset --hard command, which allows you to move the current HEAD to a specific commit and discard all changes made since that commit. This command can be useful in various situations, but it's crucial to use it with caution.
Now that you understand the basics of git reset --hard, you're one step closer to mastering Git! Stay tuned for more in-depth Git tutorials on CodeYourCraft. 🎉
Happy coding! 💻