Occasionally you'll find yourself in a situation where you've written some code, created some files, and done a whole bunch of work, only to realize that you don't need it, or don't want it anymore. Now you've got to clean up your working directory.
git checkout command can get you part of the way there, as can
git reset. But these won't handle any new objects you've created. So rather than manually cleaning things up, take advantage of some additional options Git provides.
These two commands will reset your repository and clean up all of the things you haven't checked in yet:
$ git reset --hard HEAD $ git clean -f -d
The first command reverts all of your changes to the code. You're probably familiar with that. The second command removes any new files and directories you've created.
Give it a try. Create a new repository:
$ mkdir -p testing && cd !$ $ git init
Add some code:
$ echo "this is a file" > README.md $ git add README.md $ git commit -m "initial import of readme"
Now add a new directory and a file:
$ mkdir lib $ echo "this is another file" > lib/file.txt
Then make a change to the
echo "This is a second line" >> README.md
git status to see the state of your repository:
$ git status On branch master Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git restore <file>..." to discard changes in working directory) modified: README.md Untracked files: (use "git add <file>..." to include in what will be committed) lib/ no changes added to commit (use "git add" and/or "git commit -a")
So from this output you see there's a change to the
README.md file and a new
lib folder Git doesn't know about.
To throw all this away, execute the
git reset and
git clean commands. Run them sequentially with
&& which runs the
clean command if the
reset command succeeds:
$ git reset --hard HEAD && git clean -f -d
You'll see this message, letting you know it worked:
HEAD is now at 2949ebf initial import of readme Removing lib/
lib directory and its contents are gone, as is your change to the
Since the command to clean things up is a lot of typing, open your
~/.gitconfig file and add an alias for it:
[alias] trashit = !git reset --hard HEAD && git clean -f -d
With the alias in place, you can run
git trashit to clean things up.
This cleanup approach is handy if you've used CLI tools to generate new files in your project and you made a mistake, or for other situations where you just want everything put back the way it was.