Running a shell command inside an AppleScript wrapper from Apple Automator

Started by Skids, February 05, 2025, 06:13:35 AM

Previous topic - Next topic

Skids

Hi,
I have a working exiftool command that copies, updates metadata and renames image file stored in one directory into a new directory on a different volume.  I'm running this command as a shortcut generated by Apple's Automator Application.

The present shortcut is fine except when it processes image files that have already been processed.  The attempt to create duplicate filenames throws an error that lists all the images that have not been created.  This is not a problem as all the other files are processed correctly.  However it would be great to be able to trap and present the error message in a better way.

My plan is to run the shell script from within an Applescript which will trap the error and present a more useful message, something along the lines of "37 files were not processed as they already existed in the destination folder".  Hopefully you get the idea.

Here is the fully working shell script that can be run inside an Automator Shortcut.  The shortcut starts with the path to the folder selected in the Finder and this path is passed to the shell script by Automator.
/usr/local/bin/exiftool  -m -r '-XMP:TransmissionReference<Filename' '-copyright<(c)${CreateDate#;DateFmt("%Y")} Simon Knight All rights reserved.' '-XMP:PreservedFilename<Filename' '-XMP:Title<Filename' '-IPTC:ObjectName<Filename' '-FileName<CreateDate' -d /Volumes/Images_Disc_02_Master/TempTestImageUpdated/%Y_%m/%Y_%m_%d_%H%M%S_%%f.%%e "$@"
I have copied this into an Do Applescript section of an Automator shortcut and it looks like this:
on run {input, parameters}
    display dialog "Input is set to : " & input
    --display dialog "parameters is set to : " & parameters
   
    set Mycmd to "/usr/local/bin/exiftool  -m -r '-XMP:TransmissionReference<Filename' '-copyright<©${CreateDate#;DateFmt(\"%Y\")} Simon Knight All rights reserved.' '-XMP:PreservedFilename<Filename' '-XMP:Title<Filename' '-IPTC:ObjectName<Filename' '-FileName<CreateDate' -d /Volumes/Images_Disc_02_Master/TempTestImageUpdated/%Y_%m/%Y_%m_%d_%H%M%S_%%f.%%e '$@' " & input
   
    do shell script (Mycmd)
    --return input
end run

When run the Applescript posts an error stating that it is unable to find the file, followed by the path to the selected folder (please see attached screen shot).

I have experimented with how the "$@" is entered and have tried single quotes, escaped double
quotes and using the Applescript constant 'quote' & "$@" & 'quote' but unfortunately so far I have been unable to get the script to run.

Any thoughts ?

Screenshot 2025-02-05 at 11.00.15.png

Phil Harvey

This is really an AppleScript question.  Maybe someone here knows the answer, but I think you would be better off asking in an Apple forum.

- Phil
...where DIR is the name of a directory/folder containing the images.  On Mac/Linux/PowerShell, use single quotes (') instead of double quotes (") around arguments containing a dollar sign ($).

Skids

Fair enough, I was of two minds whether I should post here or on MacScripter.

best wishes

S

StarGeek

I ran this through ChatGPT and it made these changes. I can't test it to see if ChatGPT is hallucinating or not, as I'm not on a Mac.

    display dialog "Input is set to: " & input
    -- display dialog "parameters is set to: " & parameters

    -- Ensure the input is properly escaped
    set escapedInput to quoted form of input

    -- Construct the shell command
    set Mycmd to "/usr/local/bin/exiftool -m -r '-XMP:TransmissionReference<Filename' '-copyright<©${CreateDate#;DateFmt(\"%Y\")} Simon Knight All rights reserved.' '-XMP:PreservedFilename<Filename' '-XMP:Title<Filename' '-IPTC:ObjectName<Filename' '-FileName<CreateDate' -d /Volumes/Images_Disc_02_Master/TempTestImageUpdated/%Y_%m/%Y_%m_%d_%H%M%S_%%f.%%e " & escapedInput

And said
QuoteKey Changes

    quoted form of input: Ensures that the input variable is safely escaped when passed to the shell.
    Removed $@: AppleScript doesn't support this syntax directly. The input variable already holds the file path, so there's no need for $@.
"It didn't work" isn't helpful. What was the exact command used and the output.
Read FAQ #3 and use that cmd
Please use the Code button for exiftool output

Please include your OS/Exiftool version/filetype

Skids

Solved it!

The input from Automator is interpreted by AppleScript as being of class 'list' and this needs converting to a POSIX path using the following extra line:

set tfolderpath to POSIX path of inputthen new variable tfolderpath replaces variable 'input' in the shell command.

I have no idea why this conversion is not required when using the 'do as shell command' Automator Step, just one of those things.

best wishes
Simon

Skids

#5
#StarGeek Thanks for searching ChatGPT and posting the results here.  I tried its suggestion but the initial conversion throws an error.

best wishes

S
Screenshot 2025-02-05 at 15.48.38.png

Skids

Hi,

I have finished experimenting with my Applescript that calls exiftool to copy and rename image files stored on an SD card to a disc used as an image library.

The exiftool script also populates a number of tags with the original filename as well as updating the copyright message (for times when the cameras own copyright has not been updated).

I have split the command up over several lines to make it simpler to both edit and understand what it does.

The command reads the capture date from the image file for use in both the copyright string and in the rename process.  Image files are renamed to yyyy_mm_dd_HMS_originalName.ext and are copied to sub folders /yyyy/yyyy_mm/.

So file 123456.dng shot today, 6th Feb 2025 at 1634 and stored on an SD card will be copied and renamed to "/Volumes/Images_Disc_02_Master/TempTestImageUpdated/2025/2025_02/2025_02_06_1634_123456.dng

Note the exiftool creates the subdirectories as needed.

The {input} is Automator's way of passing a folder path into the Applescript, unfortunately the path is in HFS format which looks like a list class and has to be converted into a more useful POSIX path in the first line of Applescript.  Beware of spaces in file paths as I don't use them so have not tested if POSIX path escapes them correctly.

The code in the error section counts how many files have not been processed because copies already exist in the destination folder.

on run {input}
    set tfolderpath to POSIX path of input
   
    try
        #Build exiftool command string
        set cmd to "/usr/local/bin/exiftool  -m -r "
       
        # Store original file name in tag TransmissionReference
        set cmd to cmd & "'-XMP:TransmissionReference<Filename' "
       
        # Update the copyright based on the year the image was taken
        set cmd to cmd & "'-copyright<©${CreateDate#;DateFmt(\"%Y\")} Simon Knight All rights reserved.' "
       
        # Store original file name in Adobe (only) XMP tag PreservedFilename
        set cmd to cmd & "'-XMP:PreservedFilename<Filename' "
       
        # Store original file name in tag Title
        set cmd to cmd & "'-XMP:Title<Filename' "
       
        # Store original file name in IPTC tag Objectname
        set cmd to cmd & "'-IPTC:ObjectName<Filename' "
       
        # Start of the rename the files commands using the createdate tag stored in image file
        # Note the -d tag/command is used to format the create date in following path
        set cmd to cmd & "'-FileName<CreateDate' -d "
       
        # Path to image library - modify to library folder.  Note creates sub folders as required
        set cmd to cmd & "/Volumes/Images_Disc_02_Master/TempTestImageUpdated/" -- NOTE NO SPACE AT END!!!
       
        # Next line specifies the sub folders and filename to be used,
        # %Y is four digit year, %m month, %d day %H%M%S are hour minutes seconds,
        # %%f is original filename and %%e is original extension.
        set cmd to cmd & "%Y/%Y_%m/%Y_%m_%d_%H%M%S_%%f.%%e "
       
        set cmd to cmd & tfolderpath
       
        do shell script (cmd)
        say "Copying of image files to library folder is complete."
    on error errormessage
        say "an error has occured."
        --display dialog "Here is the Error Message " & errormessage
        set tErrorLines to (paragraphs of errormessage)
        set errorCount to count of tErrorLines # number of errors / lines
       
        # Get just the lines containing "already exists
        --set AppleScript's text item delimiters to theSearchString
        --set theTextItems to every text item of tErrorLines
       
        set tPosn to -1
        set duplicates to 0
        set otherErrors to 0
        repeat with i from 1 to number of items in tErrorLines
            set tLine to item i of tErrorLines
            if tLine = "" then exit repeat
            # Search tline for the text "already exists"
            set tPosn to (offset of "already exists" in tLine)
            if tPosn > 0 then
                # attempting to duplicate an image file so just count it
                set duplicates to duplicates + 1
            else
                # an unexpected error
                set tOtherError to tOtherError & tLine & return
                set otherErrors to otherErrors + 1
            end if
            set tPosn to -1
        end repeat
       
        set tMessage to ""
        if duplicates > 0 then
            set tMessage to (duplicates as string) & " image files were not ingested as they already exist in destination folder." & return
        end if
       
        if otherErrors > 0 then
            tMessage = (tMessage & otherErrors as string) & " other errors were reported :" & return & tOtherError
        end if
        say tMessage
        display dialog tMessage
    end try
end run

The Automator shortcut is attached.  To use on your computer you need to edit the path to library part to reflect the location of your image library as well as putting your name into the copyright string.

I hope the code is of interest.  Now I am going to try and create an Apple Shortcut that does the same as I read that Shortcuts is replacing Automator sometime in the future.

best wishes

Simon