Search code examples
applescript

Loop happens when trying to add string to a filename via AppleScript


I am trying to write an AppleScript that can add the current time to a folder's name.

on adding folder items to this_folder after receiving these_items
    repeat with this_item in these_items
        tell application "Finder"
            set t to (time string of (current date))
            set name of this_item to (t & " " & (name of this_item))
        end tell
    end repeat
end adding folder items to

I have added the script as a Folder Action for a specific folder so it will automatically rename every folder that is being put into it. But when I add a folder to the one with the script as a Folder Action the time is being added repeatedly until the folder's name is too long to add more characters to it. How can I make it so the time is only being added once?

Thank you in advance!


Solution

  • The problem is that every time the folder gets renamed, it triggers the Folder Actions to kick in again. My solution would be to disable the Folder Actions when items get added to the trigger folder, then after the folders get renamed... re-enable folder actions. This way the already re-named folders don't re-trigger the Folder Action to rename the already re-named folders.

    This following AppleScript works for me.

    on adding folder items to this_folder after receiving these_items
        set t to (time string of (current date))
        tell application "System Events"
            set folder actions enabled to false
            repeat with this_item in these_items
                set name of this_item to (t & " " & (name of this_item))
            end repeat
            set folder actions enabled to true
        end tell
    end adding folder items to
    

    NOTE: It's good practice to use System Events instead of Finder, anytime you can.