I’m very new to Applescript but have used other scripting languages over the last five years. I wrote a quick script that deletes some files/directories based upon file name matches and modification date. I did also test it a few times but I’m now under the impression that it is either badly written or dangerous, in the sense that it may delete more than necessary.
If you’re a pro scripter, can you please tell me if there’s anything wrong with my script? Is it unsafe? I’ve been led to believe that after speaking to a colleague who believes it’s done some ‘damage’.
Here’s the script:
set my_path to "Macintosh HD:Users:infmz:Backups"
tell application "Finder"
delete (every item of folder my_path whose modification date is less than ((get current date) - 4 * days) and name contains "backup_id")
empty trash
end tell
Specifically, I am trying to delete backup folders that are older than three days. All such folders contain the string “backup_id” in their names.
If this is the entirety of the script, then I would say the one “unsafe” item that really jumps out to me is that you are not parsing the folder path to ensure the script isn’t being directed to a vital folder, like “Macintosh HD:System:” or “Macintosh HD:Library:”.
The other thing is that I don’t think the script does a good enough job parsing files before deleting. This is more a matter of approach, but if it were me, I would generate a list of initial target files first (see “Get full directory contents with AppleScript”), and then parse that list for actual targets for deletion.
Also, I would generate a log of actions taken and remove the “empty trash” command to allow the user a chance to double-check the actions of the script before final deletion.
It would be helpful to describe what damage was observed by the other user.