You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决AppleScript调用zip命令创建压缩包失败的问题

错误原因

  • 命令连接符使用错误:你在cd和zip命令之间用了管道符|,管道符的作用是将前一个命令的输出传递给后一个命令,并不会让后一个命令在前一个命令切换后的目录下执行,最终zip命令运行在默认工作目录,找不到目标文件夹。
  • 压缩文件名转义错误:你手动给myZipName加了单引号,没有使用AppleScript标准的quoted form of做转义处理,当文件夹名称包含空格、特殊字符时,shell会解析错误,无法识别完整的文件名。

修复方案

你可以直接使用以下修正后的脚本:

tell application "Finder"
    set myDir to choose folder
    set myParentDir to the parent of myDir as alias
    set myParentPath to POSIX path of myParentDir
    set myDirName to the name of myDir
    set myZipName to myDirName & ".zip"
    -- 统一用quoted form处理所有需要传入shell的路径/文件名
    set quotedZipName to quoted form of myZipName
    set quotedDirName to quoted form of myDirName
    set quotedParentPath to quoted form of myParentPath
    -- 用&&连接命令,只有cd执行成功才会运行zip
    set myShellScript to "cd " & quotedParentPath & " && zip -r " & quotedZipName & " " & quotedDirName
    do shell script myShellScript
end tell

补充优化(可选)

如果需要完全对齐Finder右键的压缩效果,推荐使用macOS自带的ditto命令代替zip,它会自动处理macOS专属的文件元数据、资源叉、隐藏文件等内容,和系统默认压缩行为完全一致,对应shell语句修改为:

set myShellScript to "cd " & quotedParentPath & " && ditto -c -k --sequesterRsrc --keepParent " & quotedDirName & " " & quotedZipName

内容的提问来源于stack exchange,提问作者Timothy Sheasby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 19:36:04