tagsapplescriptfinder

Changing Finder Labels with AppleScript


I want to assign specific tags to selected files in Finder (OS X 10.9.4), using AppleScript and tag, but I'm having problems passing the file path to tag.

tell application "Finder"
    try
        repeat with currentFile in items of (get selection)
            if label index of currentFile is 0 then
                do shell script ("/usr/local/bin/tag -a 'foo' " & currentFile)
            else
                set label index of currentFile to 0
            end if
        end repeat
    on error e
        return e
    end try
end tell

If I have /Users/fort/bar.txt selected in Finder, I get the following error:

"tag: The file “/Users/fort/bar.txt” couldn’t be opened because there is no such file."

However, the following code does change the tag of the specified file to foo:

set myFile to "/Users/fort/bar.txt" do shell script ("/usr/local/bin/tag -a 'foo' " & myFile)

Any idea why currentFile isn't being passed to tag in a way it can parse? Thanks.

fort


Solution

  • It's a path problem, you must convert Finder item to a string, and convert the HFS path to posix path

    Try this

    tell application "Finder"
        repeat with currentFile in (get selection)
            tell currentFile
                if label index is 0 then
                    my tagCmd(it as text) -- convert Finder item e.g. file "bar.txt" of folder "fort" of.... -->  "MBA:Users:fort:bar.txt” (path with colon)
                else
                    set label index to 0
                end if
            end tell
        end repeat
    end tell
    
    on tagCmd(f)
        do shell script "/usr/local/bin/tag -a 'foo' " & quoted form of POSIX path of f -- posix path convert path with colon to use in shell
    end tagCmd