Git version controlling system lets you discard and undo mistakes that happen in several stages such as “working directory”, “stage/index”, “history” and “remote”. In this question, we are going to discard and undo changes in the working directory. In other words, discard the changes that are not yet staged in the repository. If you need to discard staged changes, refer to this question.
First, initiate a local Git repository with the
git init command or use an existing repository that you have.
Clean Newly Created Unstaged Files
Create a couple of sample files and add some content to them. If you need, you can use the following command for that. It will create a file called
file.txt and will add “Test Content” to it. Repeat the command a few times with different file names to create a few files.
echo "Test Content" > file.txt
Now we call these files are “untracked”, “unstaged” and in the “working directory”. You can confirm it by running the
git status command.
Let's say, you just accidentally created these files and now want to remove them all. We can easily undo such situations quickly with the
git clean -df command. It will discard all the newly created files and directories in the working directory.
git clean -df
If you only need to remove some specific files, you can mention them like this.
git clean -df file1.txt file2.txt
After that, you can use the
git status to check whether everything is cleaned and in its original state.
Discard Unstaged Changes Of Existing Files
Let's say, this time you have changed some committed files in the repository and now need to undo those changes. For the demonstration, again create some sample files (you may use the earlier mentioned command to create files). Stage them using the
git add . command.
git add .
Commit the files using the
git commit command. We are using the
-m to mention the commit message.
git commit -m "Add new files"
Now change some content in these committed files. Then run the
git status to confirm whether there are modified files. After that, run the following command to clean and undo all the changes you made to files.
git checkout -- .
If you only need to discard some specific files, you can mention them like this.
git checkout -- file1.txt file2.txt
Alternatively, you can use the
git reset command with
--hard as well. It will discard and clean both staged and unstaged modifications of existing files in the repository.
git reset --hard