0

I'm making a bash file to remove all .class files that java generates inside the src folder and it's subfolders. The structure is:

project
   src
      /utils
         utils.class
      /game
         game.class
         gameManager.class

So when I execute the script inside the project folder, it search all .class files and remove them, but it doesn't work.

I just created this script:

find . -path "src/*/*" -name "*.class" -exec rm -f {} \;

How can I fix it?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255

2 Answers2

6

It doesn't work because the path won't start with src, it will start with ./src.

Your command line can be corrected into this:

find . -type f -path "./src/*/*" -name "*.class" -exec rm -f {} \;

Alternatively,

find . -type f -path "./src/*/*" -name "*.class" -delete

If you're happy deleting all *.class files anywhere under src (not just in subdirectories thereof):

find src -type f -name "*.class" -delete
Kusalananda
  • 333,661
  • Has the first line the same behaviour that the second one? – Albert Lazaro de Lara Mar 20 '17 at 16:07
  • 1
    @albert Yes. I just added -type f, because -delete will also remove directories whereas rm -f won't (on the off chance that you have a directory whose name matches the pattern). – Kusalananda Mar 20 '17 at 16:09
  • I'm looking for one last thing: find return any value? so if it found something returns 0 or if it doens't find a file it reutrns a -1 or 1? – Albert Lazaro de Lara Mar 20 '17 at 16:17
  • 1
    @albert find exits with an exit code of 0 if no errors occurred. This is regardless of whether it found anything or not. You may add -print before or after the -delete and redirect the output to a file. Testing the size of this file afterwards will tell you whether it did anything or not. Test this with test -s find_output.txt && echo 'Files were removed' or something similar. – Kusalananda Mar 20 '17 at 16:21
1
cd ./project/src && \
find . -name '*.class' -exec rm -f {} \;

No need to complicate simple things.