kurone-kito
kurone-kito

Reputation: 93

Git: Exclude some files when ran git clean

I want to clean up files which ignored by .gitignore, but I want to exclude some files specified by excluding options. And then, I don't want to remove untracked files.

dist                     (ignored)
node_modules             (ignored)
.env                     (ignored but I want to exclude for the cleanup)
I_do_not_want_add_yet.js (untracked, I don't want cleanup some untracked files)
package.json             (There are many other tracked files)

So I looked into some posts and tried the following command:

$ git clean -ndX -e .env
Would remove dist/
Would remove node_modules/
Would remove .env   # Oops!

$ git clean -ndX --exclude='!.env'
Would remove dist/
Would remove node_modules/
Would remove .env   # Oops!

$ git clean -ndx -e .env
Would remove dist/
Would remove node_modules/
Would remove I_do_not_want_add_yet.js   # Oops!

Do you have good ideas?

Upvotes: 6

Views: 1531

Answers (2)

Robert
Robert

Reputation: 2824

you can use

git clean -dnx -e /.env -e I_do_not_want_add_yet.js using double exclude

but if the file name is generic you will have many files in the node_modules matching it so you should use the full path and start with /

git clean -dnx -e /.env -e /path-to-file

Upvotes: 2

kurone-kito
kurone-kito

Reputation: 93

The problem could solve using the command, which is a little hacky:

git ls-files --other --ignored --exclude-standard \
  | grep -v -E "^\.env" \
  | xargs -I{} rm -rf {}

Upvotes: 1

Related Questions