Smith Dwayne
Smith Dwayne

Reputation: 2807

Git delete all unmodified files

I am using git in my project at Linux platform. I have plenty of files in a particular directory. I modified some 50 above files in that directory and didn't stage and commit it. I wish to delete all other unmodified files from that directory? Is there a way to do this, using git and Linux Commands?

Upvotes: 1

Views: 1350

Answers (5)

jthill
jthill

Reputation: 60393

git ls-files -m | git ls-files -zX /dev/stdin | xargs -0 rm

Upvotes: 0

sanchay shukla
sanchay shukla

Reputation: 1

To do the opposite: How can I discard modified files?

git reset --hard [HEAD] 

Upvotes: 0

michael
michael

Reputation: 9799

Using git clean is what you want. To remove (-x) those files and directories (-d), run:

$ git clean -fdx

If you use the -X option instead of -x, then the files you have told git to ignore will still be kept (e.g., build artifacts). Recent versions of git require either "-f" (force) or "-n" (dry-run) to be specified.

You should run a dry-run first, to show what will happen, but not actually do anything:

$ git clean -ndx

I use this so often, that I have an alias for this (added to your .gitconfig) to check for files that would be deleted when you run git clean. It's also useful to remind me if I've forgotten to "git add" a file that I want to keep.

[alias]
     # list files that would be removed via 'clean' (non-destructive)
     ifc = clean -ndx

Then, running git ifc (i.e,. "ifc" = "if clean") shows everything that isn't tracked and could be removed, or isn't tracked and should be added.

https://git-scm.com/docs/git-clean

Upvotes: 0

CodeWizard
CodeWizard

Reputation: 142352

You can also use more simple commands for this purpose:

git clean -Xfd // capital X
git clean -xfd // lower x

It will clean your working directory from the desired files.

enter image description here

Upvotes: 0

xxfelixxx
xxfelixxx

Reputation: 6602

Not sure why you would want to do this.... but you can:

# Save changes to stash
git stash save

# Remove everything left
rm -rf ./*

# Checkout (restore) all of the changed files
git stash show --stat | grep -v changed | sed -e 's/|.*$//;' | xargs git checkout

# Restore the changes to those files
git stash pop

Upvotes: 4

Related Questions