As a developer, we must have used Git. Git is a powerful version control tool that allows us to manage changes in our code, we can update our code, discard the changes revert to the previous commit, and a lot. In this article, we’ll walk through the process of discarding the local changes in Git.
Step 1: Check the status
Open the terminal in your project directory (git initialized) and run the following command:
$ git status
This command will display all the changes to the repository locally on your machine. This includes:
- Modified files
- Stagged files
- and Untracked files
Now, we’ll go through various methods of discarding the local changes.
Discarding all local changes
To discard all local changes at once and revert back the directory state to the latest commit (made to origin). We have to use git checkout
preceding double-dash with a full-stop ( . )
$ git checkout -- .
*p.s Here .
indicates the current directory.
Discard Unstaged Changes
To discard the changes that are currently not staged can be discarded by git checkout
along with specifying the <filename>
.
$ git checkout -- app.py
Simply, git checkout -- <filename>
will revert the changes in the state of the previous commit.
Discard Staged Changes
To discard the staged changes and return to the previous commit state, use git reset
.
$ git reset HEAD app.py
The general command is:
$ git reset HEAD <filename>
Final Step: Check Status
Once you discarded your changes, run the command git status
. It will display the changes made to the repository, if you have discarded all the changes, it will be displayed nothing to commit, working tree clean
.
$ git status
Conclusion
In conclusion, Git provides several methods to discard local changes, allowing developers to maintain code integrity. You can use git checkout -- .
to discard all changes, git checkout -- <filename>
to discard unstaged changes, and git reset HEAD <filename>
to discard staged changes. After discarding changes, verifying with git status
ensures a clean working tree. Git’s flexibility empowers developers to efficiently manage their codebase and collaborate effectively.
Thanks for reading! Have a wonderful day! and as always Happy coding!