Languages
[Edit]
EN

Git reset hard with untracked files removal

5 points
Created by:
Root-ssh
175020

1. Git reset hard and remove all untracked files and directories

# reset current branch and remove untracked directories and files
git reset --hard HEAD && git clean -fd
  • This cmd will reset our branch and remove all untracked files and directories (non-ignored by .gitignore).
  • All uncommited changes will be removed and we have clean state on the branch.
  • Very powerful command, before using it think twice.

 

Practical example on some temporary files:

Git reset hard and remove all untracked files and directories
Git reset hard and remove all untracked files and directories

If we want to remove all files and directories (even ignored by .gitignore - it will also remove all IDE configurations if stored under project), below command can do the trick:

# reset current branch + remove ignored and non-ignored files
# it will remove all ignored files like .idea configs etc
git reset --hard HEAD && git clean -fdx

# reset current branch + remove ignored directories and files
git reset --hard HEAD && git clean -fdX

# reset current branch + remove directories
git reset --hard HEAD && git clean -fd

2. Explanation of git reset --hard HEAD

$ git reset --hard HEAD

Git will leave untracked files.

3. Explanation of git clean -fd

git clean most useful flags:

-n, --dry-run         dry run
-f, --force           force
-d                    remove whole directories


git clean -help entire output:

$ git clean -help
usage: git clean [-d] [-f] [-i] [-n] [-q] [-e <pattern>] [-x | -X] [--] <paths>...

    -q, --quiet           do not print names of files removed
    -n, --dry-run         dry run
    -f, --force           force
    -i, --interactive     interactive cleaning
    -d                    remove whole directories
    -e, --exclude <pattern>
                          add <pattern> to ignore rules
    -x                    remove ignored files, too
    -X                    remove only ignored files

4. Explanation of git clean --dry-run

$ git clean --dry-run

This command will list what will be deleted.
It is useful to run it before running git clean -fd.

5. References

  1. git reset - Docs
  2. git clean - Docs

Alternative titles

  1. git reset hard untracked files
  2. git reset hard still shows untracked files - how to solve it and reset all
  3. git reset hard dirask
  4. git reset hard all files
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Git

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join