Discarding unstaged changes in Git is useful when you want to revert changes that have not yet been staged for a commit. This guide explores various methods to discard these changes efficiently and safely.
Understanding unstaged changes
Unstaged changes refer to modifications in your working directory that Git has not yet recorded in the staging area. These can include new files (untracked) and modifications or deletions to existing tracked files.
Methods to discard unstaged changes in Git
Discarding unstaged changes in a specific file
If you want to discard changes in a specific file and revert it to the version in your last commit, use the
git checkout
command:Terminal$ git checkout -- <file-name>For example, to discard changes in
example.txt
:Terminal$ git checkout -- example.txtThis command will restore
example.txt
to the state it was in at the last commit, removing any unstaged changes.Discarding all unstaged changes
To discard all unstaged changes across your entire repository,
git restore
is the recommended command starting with Git version 2.23:Terminal$ git restore .This will revert all modified and deleted files in your working directory to their last committed state. It's a powerful command that should be used with caution, as it will eliminate all current modifications that haven't been staged.
Using
git clean
to remove untracked filesSometimes, you might also want to clean up untracked files, such as build outputs or new files that have not been added to Git. The
git clean
command can be used for this purpose. It's important to be very careful with this command because it removes files permanently.To see which files would be removed (a dry run):
Terminal$ git clean -nTo remove untracked files permanently:
Terminal$ git clean -fTo remove untracked directories in addition to untracked files:
Terminal$ git clean -fd
Best practices when discarding changes
- Check changes before discarding: Always review which changes are going to be discarded to prevent accidental loss of important work. You can see a list of unstaged changes by running
git status
. - Use versioning in your development: Regularly commit your work in meaningful increments. This habit keeps your changes organized and reduces the risk of needing to discard large amounts of work.
- Backup before bulk operations: Before running commands that discard changes across many files, consider creating a backup branch or stashing your changes (using
git stash
) just in case you need to retrieve something later.
For further reading on discarding unstaged changes in Git, see the official Git documentation.