How to discard local changes in Git

Remove uncommitted changes in Git

Git offers you several commands to discard local changes in your working directory. These include the following:

  • The git stash command, which saves uncommitted changes and reset your workspace.
  • The git reset command, which only touches tracked files.
  • The git clean command, that deletes every untracked file.

The git clean command is dangerous, destructive and unrecoverable. In most cases, a developer must only use a git stash or a hard git reset to discard local changes and revert their workspace back to its state before a prior commit occurred.

Apply git stash to discard changes

The easiest way to restore your working directory and discard any local changes is to issue a git stash command.

This not only discards all local changes, but it also stores a record of your changes for future retrieval with a pop or apply command.

discard@changes:~/git-example$ git stash
Saved working directory and index state

However, if you do not want your changes stored, the git reset command is a better option.

discard local git changes

A git reset and stash will work in tracked files, but not untracked files or files listed in a .gitignore file.


Use git reset to delete uncommitted changes

A simple git reset command with the hard flag will accomplish the following tasks:

  • Revert all tracked files to their state at the last commit.
  • Clear the Git index of all staged files.
  • Leave any untracked or ignored files alone.

Git reset hard to discard changes

To use the git reset command to discard all local changes, simply type in the following command in a terminal window:

discard@changes:~/git-example$ git reset --hard
HEAD is now at ebbbca3 Discard local changes example

Use the soft flag with the reset command, and this will not remove changes to tracked files.

discard local git changes

The git reset command discards all changes to tracked files and also resets the index.

Git reset doesn’t discard all local changes

The git reset –hard command reverts uncommitted changes that exist in files that have been added to the index,. This includes files that are newly created files, or files that were previously added to the index and edited since the last commit.

However, any new files created in the local Git workspace that have never been added to the index will remain in the project folder after the hard reset.

Git clean with caution

To remove untracked files, you need to use the git clean command.

However, this command will delete all untracked files, regardless of whether they were recently changed or not.

If removal of untracked files is what you need, TheServerSides’s git clean tutorial will provide you insights on how to use the command safely through the use of dry runs and interactive deletions.

App Architecture
Software Quality
Cloud Computing
Security
SearchAWS
Close