How to Remove Local Git Changes
This article discusses the various methods we can employ to discard local changes in Git. We will see how you can do away with the following local changes assuming we had cloned a repository.
- Staged Changes
- Unstaged Changes
- Untracked Changes
- Committed Changes
- Committed and Pushed Changes
Various Methods Used to Remove Local Git Changes
Assuming we have just cloned a Git repository, made a few file changes, and staged the files for commit, how do we discard the same?
We can discard staged changes with the git reset
command with the --hard
flag. Run the command as illustrated below.
$ git reset --hard
In the next scenario, we have made changes to some files in our repo, but we have not yet staged for commit. How do we discard these changes?
We have two options; we can either use the git reset --hard
command or the git checkout <file>
command. If you are dealing with multiple files, run the latter, as shown below.
$ git checkout .
This will instruct Git to restore all files as they were in their last committed state hence discarding the unstaged changes.
Take another scenario where we have introduced new files to the repository. These files will fall under untracked files.
How do we do away with these files?
The git clean
command does the job. Here is how you can run the command.
$ git clean -f
The effects of this command cannot be reversed. It is advisable to run the command as a dry run to see what will be lost.
You can run the command as illustrated below.
$ git clean -f -n
You can add the -d
flag to remove untracked directories.
Bonus Tip
If you do not want to discard the changes but want them off the index, you can stash them. Stashing in Git means storing the changes from the index safely somewhere else.
When you need them back, run the git stash pop
command.
What if we have already committed some changes and need to eliminate them?
At this point, we will need to move the HEAD
pointer to the parent node of the recently created commit. We will use the git reset --hard
command, as shown below.
$ git reset --hard HEAD~1
This will do away with the changes introduced by the commit at HEAD@{0}
.
You can also run the git reset --hard@{u}
to discard local commits in a branch and make it identical to the upstream tracking branch.
If you have already committed the changes, you can create a commit that reverts the changes introduced to the files and push it to the remote.
$ git revert <commit-hash>
This will create a new commit, and you can push it to the remote.
In a nutshell, there are various methods we can employ to do away with local Git changes. Be careful when working with public repositories.
John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.
LinkedIn