Search code examples
applescript-objc

How to Zip folder with AppleScript-objc?


I'm generating a few Logs on the system, and then copying it to /tmp/MyFolder, and then I move the folder to the desktop, I'm trying to compact it before you move on, but I don't know how to do it, I have tried the following:

tell application "Finder"
    set theItem to "/tmp/MyFolder" as alias
    set itemPath to quoted form of POSIX path of theItem
    set fileName to name of theItem
    set theFolder to POSIX path of (container of theItem as alias)
    set zipFile to quoted form of (theFolder & fileName & ".zip")
    do shell script "zip -r " & zipFile & " " & itemPath
end tell

Solution

  • While this isn't an AppleScript-ObjC script, I'm posting the corrected version of your own script so that it functions to do as you described:

    tell application "System Events"
        set itemPath to "/tmp/MyFolder"
        set theItem to item itemPath
        set fileName to quoted form of (get name of theItem)
        set theFolder to POSIX path of (container of theItem)
        set zipFile to fileName & ".zip"
    end tell
    
    do shell script "cd " & quoted form of theFolder & ¬
        "; zip -r " & zipFile & space & fileName & ¬
        "; mv " & zipFile & space & "~/Desktop/"
    

    Trying to avoid using Finder for file system operations. It sounds counter-intuitive, but it's not well-suited for it. Use System Events, which has—among many other benefits—the ability to handle posix paths.

    The script now zips the folder and its containing items into an archive at /tmp/MyFolder.zip, then moves this archive to the desktop.