How to Discard Unstaged Changes
There are times while working on a project, and you figure out that you made mistakes and need to undo everything. In this tutorial, you will get all answers concerning the discard of the unstaged changes in the working copy.
We suggest a fast way using the git stash command:
git stash save --keep-index --include-untracked
Use the git stash drop drop command to discard it.
Another way of discarding unstaged changes. For all unstaged files in the current working directory git checkout can help:
git checkout -- .
For undoing a specific file run:
git checkout -- filepath
For removing unstaged files and directories, follow the steps. At first, run git clean with the -n option to preview files and directories that should be removed to make sure you don’t need them. Then run the following to remove untracked files and directories:
git clean -nd git clean -fd
This will delete the files and directories but cannot remove files listed in .gitignore (e.g., the temporary files not tracked by Git.).
To delete all the files and directories use the git clean command:
git clean -ndx git clean -fdx
Staged and Unstaged Changes
The staging area (index) is a container where Git gathers all changes which will be part of the next commit.
Editing a versioned file on the local machine, will be recognized by Git as a modified file and be called as unstaged. Staging the file will place the file into the staging area. The changes within the staging area are part of the next commit. The next git commit will transfer all items from the staging area into your repository. The staging area allows collecting all changes to get a clean commit.
The git stash command shelves changes made to your working copy so you can do another work, get back, and re-apply them. It takes both staged and unstaged changes, saves them for further use, and then returns them from your working copy. You can delete the stash with git stash drop. To remove all the stashes, you should use git stash clear.
The git clean is an undo command that completes other commands like git reset and git checkout. Unlike the other commands, this command operates on files already added to the Git staging area and runs on untracked files. Untracked files are those created within the working directory but are not yet added to the staging area.
Git Checkout vs Git Checkout --
The git checkout command switches branches or restores working tree files. It operates on files, commits, and branches and allows switching between multiple features in just a single repository. The command works with the git branch command. It updates the files in the working directory to match the version stored in that branch, instructing Git to record all the new commits.
The “--” with git checkout is a way to instruct Git what follows checkout to treat as a file, not a branch. It is used when, for example, you have a file and a branch with the same name.