Bash – compress all pdf files recursively

bashfindshell

i want to compress all my pdf files in an given directory and its sub-directories using ghostscript.

I´m stuck using the find command within loops by filename including spaces.

Here some example code I´m aiming for:

pdffiles=$(find /path/to/directory -type f -name *.pdf)
for file in pdffiles; do
  gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/screen -dNOPAUSE -dBATCH -dQUIET -sOutputFile=new_$file $file; 
  rm $file;
  mv new_$file $file;
done;

Any idea how i could fix the problem with the spaces? Is there a better way to do this?

Best Answer

Your loop is better written as

find ... | while read -r file

But then you need to make sure you quote the filename inside the loop. So we end up with

find /path/to/directory -type f -name *.pdf | while read -r file
do
  gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/screen -dNOPAUSE -dBATCH -dQUIET -sOutputFile="new_$file" "$file"
  rm "$file"
  mv "new_$file" "$file"
done

(Also note all those ; aren't needed).

Now this loop has potential file ownership/permission issues, but that's another question :-)

Related Question