Undoing Work
Sometimes when you’re working on a project, you might make a mistake and want to undo it. Just like using the "undo" command in MS Word, Git lets you undo changes in your project.
Undoing Local Changes Before Staging
Let’s say you accidentally added something wrong to your file. You can undo it before you save or "commit" it to the repository.
First, make sure you’re on the latest version of the project (on the master branch).
Make a Mistake: Let’s say you accidentally add this line to your index.html file:
echo "<p>This line is a mistake, let's fix it.</p>" >> index.htmlCheck the Status: To see the changes, run:
git statusYou will see something like this:
On branch master Changes not staged for commit: (use "git add..." to update what will be committed) (use "git restore ..." to discard changes in working directory) modified: index.html This tells you that index.html has been changed but hasn’t been staged yet.
Undo the Change: To undo the change and go back to the previous version, use the git restore command:
git restore index.htmlCheck the Status Again: Now, if you run:
git statusYou’ll see:
On branch master nothing to commit, working tree cleanThe file is back to its original state, and your bad line is gone.
Undoing Staged Changes Before Committing
If you’ve already staged a change but haven’t committed it yet, you can still undo it.
Make a Mistake and Stage It: Let’s add a bad line again:
echo "<p>This line is a mistake, let's fix it.</p>" >> index.htmlNow stage it:
git add index.htmlCheck the Status: Run:
git statusYou’ll see:
On branch master Changes to be committed: (use "git restore --staged..." to unstage) modified: index.html This means the change is ready to be committed.
Unstage the Change: If you don’t want to commit this change, you can "unstage" it with this command:
git restore --staged index.htmlNow, the change is no longer staged, but it still exists in your working directory.
Undo the Change: To completely remove the change from the file, run:
git restore index.htmlCheck the Status Again: After that, you can run:
git statusYou’ll see:
On branch master nothing to commit, working tree cleanYour working directory is clean, and the line with mistake is gone.