Git: How to Completely Discard Staged and Unstaged Changes?

approximately 2 minutes of reading

It is not uncommon to work on a proof of concept, where you quickly have to check something and as a result you end up with a lot of changes in your git repository. Changes that you not necessarily want to persist and commit. This may include adding new files as well as modifying or removing existing files or directories that were already committed in the past. Let me show you how to easily restore your branch to a clean state by using command line.

Notice ⚠️

By executing the following command you will lose all of the staged and unstaged changes that were made down the line.


What do you mean by saying "clean state"?

I mean a situation where you have nothing to commit and nothing to push - literally no changes made, where calling git status, outputs:

On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean
Unto Staged Changes
git reset --hard

According to the documentation, the reset command combined with --hard will:

Resets the index and working tree. Any changes to tracked files in the working tree since <commit> are discarded. Any untracked files or directories in the way of writing any tracked files are simply deleted.

The <commit> is optional and always default to HEAD.

But what the hell is HEAD?

Think of it as a pointer to the current branch you have checked out.

Undo Unstaged Changes
git clean -fd

This will remove all files and directories that are not tracked.

Convenient Alias

On a daily basis, it is probably convenient to type these two commands in a quick way as a single alias. Depending on the type of a shell you use, you could add a new alias. In my case, I use Oh My Zsh where all my aliases are stored under:

~/.zsh_aliases

Let's add a new one:

sudo vim ~/.zsh_aliases

An excerpt of my aliases looks like:

# Git
alias gs='git status'
alias gf='git fetch --prune'
alias gp='git pull'
alias gfgp='gf && gp'
alias gco='git checkout'
alias greset='git reset --hard && git clean -fd'

So I have defined a new one called greset. Save the file. Now, to make it available type:

source ~/.zsh_aliases

or open a new tab in your terminal app.

Now each time you want to revert changes you made (that were not commited), simply type greset to go back to the clean state. This should save you some time.


Words: 424
Published in: Git
Last Revision: November 29, 2022

Related Articles   📚