Search code examples
bashautomatorsips

adjusting JPEG compression levels with an Automator Service and sips - stumbles over certain file names


I've been tinkering with a script that uses sips to adjust JPEG file compression conveniently from within the Finder as a Service. It maintains file stamps unlike the simple Automator compression/rescaling functions.

Alas, it stumbles over certain file names, e.g. ones with a space and doesn't rescale them presumably because the file output chokes on the space character. So, it proceeds as expected on a file like "DSC03761.JPG" but not on "DSC03761 2.JPG". It also fails if the path contains spaces, if for example the file resides in a folder called "my Pictures".

Since I'm a noob, I haven't figured out how to adjust the script. You probably have a better idea?

screenshot of script

bash script below:

for f in "$@"; do

# Save creation date time stamp of the target file in 't'.
  t="$(/usr/bin/GetFileInfo -d "$f")"

# Compress the target file. Level 0-100 or low/normal=50/high/best
  filename=$f
  #/usr/bin/sips --setProperty formatOptions 60 $f --out ${filename%.*}.jpg
  /usr/bin/sips --setProperty formatOptions normal $f --out ${filename%.*}.jpg

# Set the modified and creation date time stamps to 't'.
  /usr/bin/SetFile -m "$t" "$f"
  /usr/bin/SetFile -d "$t" "$f"

done

# Notify user that operation is finished with a sound.
/usr/bin/afplay "/System/Library/Sounds/Purr.aiff"

Solution

  • Here, you correctly but unnecessaily quote an expansion:

      t="$(/usr/bin/GetFileInfo -d "$f")"
    

    But here, where you would need to use quotes, you don't:

      /usr/bin/sips --setProperty formatOptions 60 $f --out ${filename%.*}.jpg
    

    The latter should be

      /usr/bin/sips --setProperty formatOptions 60 "$f" --out "${filename%.*}.jpg"