1

I’m using bash shell. I have this command to delete all JAR files within a particular directory

find ~/.jenkins/jobs/subco/ -name '*.jar' -print0 | xargs -0 -r rm

However, I want to modify the above so that it will delete all JAR files except those within the “~/.jenkins/jobs/subco/myapp”. How do I modify the above command to exclude removing JAR files from that specific directory while removing from all others?

2

Use the -prune option to skip that directory

find ~/.jenkins/jobs/subco -path ~/.jenkins/jobs/subco/myapp -prune -o -name '*.jar' -exec rm -r {} +
1

Try:

(
  cd ~/.jenkins/jobs/subco
  find . -path ./myapp -prune -o -type f -name '*.jar' -print0 | ...
)

Adding -type f to restrict the condition, since when you want to match JAR files only. And also, you used -print0, it's likely that your find supports -delete, so you can use:

(
  cd ~/.jenkins/jobs/subco
  find . -path ./myapp -prune -o -type f -name '*.jar' -delete
)

POSIXly:

(
  cd ~/.jenkins/jobs/subco
  find . -path ./myapp -prune -o -type f -name '*.jar' -exec rm -f {} +
)

With GNU find, you can use -execdir to avoid -exec race condition, see also some security considerations in GNU find manual.

You should always use -delete when available.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.