AppleScript打包为.app运行时复制早于unzip完成致空文件夹覆盖错误
问题根因
打包后时序错位的核心原因
AppleScript编辑器运行时,会强制阻塞等待所有do shell script触发的子进程完全结束、文件系统操作全部落地后,再执行下一行代码。但打包成独立.app运行时,主线程会在shell进程返回退出信号后立刻继续,此时磁盘缓存还未完成刷盘,unzip解压的文件还没实际写入到目标目录,脚本就读取到了空的文件夹结构,直接触发复制操作。
现有代码的硬错误
- 复制逻辑的语法完全不符合Finder的命令规范,无法正常执行
- 下载逻辑给curl加了后台运行符
&,脚本不会等待下载完成就开始轮询状态,时序完全混乱 - 路径全部硬写了固定字符串,没有通过系统API解析用户目录,打包成.app后受沙箱权限限制容易路径错位
- 靠硬写
sleep 10等待解压完成,遇到大文件时等待时间不足会依然触发空文件夹复制,小文件时又会造成无意义的长等待
修正版可直接运行代码
-- 自动解析相对路径,无硬编码全路径 on resolveUserPath(inputPath) if inputPath starts with "~/" then return (POSIX path of (path to home folder)) & text 3 thru -1 of inputPath else if inputPath = "~" then return POSIX path of (path to home folder) else return inputPath end if end resolveUserPath -- 1. 创建临时工作目录 set tempWorkDir to my resolveUserPath("~/Downloads/OfflineResourceTemp") do shell script "mkdir -p " & quoted form of tempWorkDir -- 2. 同步下载ZIP,带基础进度输出 set zipSavePath to tempWorkDir & "/ResourcesOffline.zip" set downloadLogPath to tempWorkDir & "/download.log" -- 替换成你实际的下载地址 do shell script "curl -L -o " & quoted form of zipSavePath & " 'https://你的资源下载地址/ResourcesOffline.zip' > " & quoted form of downloadLogPath & " 2>&1" -- 3. 解压并强制刷盘,确保所有文件落地 set extractBaseDir to tempWorkDir & "/extracted" do shell script "mkdir -p " & quoted form of extractBaseDir & " && unzip -o " & quoted form of zipSavePath & " -d " & quoted form of extractBaseDir & " && sync" -- sync命令是关键:强制把所有磁盘缓存写入实体存储,从根源解决提前读空文件夹的问题 -- 4. 定位ZIP内的主文件夹(包含子文件夹、文本文件的根目录) set zipRootName to do shell script "ls -1 " & quoted form of extractBaseDir & " | head -n 1" set sourceFolderAlias to (POSIX file (extractBaseDir & "/" & zipRootName & "/")) as alias -- 5. 复制主文件夹内所有内容到目标路径,自动覆盖同名文件 set targetDir to my resolveUserPath("~/Library/Application Support/MyApp/Resources") do shell script "mkdir -p " & quoted form of targetDir tell application "Finder" duplicate entire contents of folder sourceFolderAlias to folder (POSIX file targetDir as alias) with replacing end tell -- 6. 清理临时文件 do shell script "rm -rf " & quoted form of tempWorkDir display dialog "资源部署完成" buttons {"确定"}
关键修正点
- 从根源解决打包后的时序错位:在unzip命令末尾加
sync,所有shell命令都采用同步执行模式,脚本一定会等上一步操作完全落地才继续,不会出现空文件夹被复制的问题 - 路径全兼容:所有路径通过系统API解析用户目录,没有硬编码带用户名的全路径,打包成.app后在沙箱权限下可正常识别
- 复制逻辑合规:使用Finder原生的
duplicate ... with replacing语法,实现跳过ZIP内主文件夹、仅复制内部子文件/子文件夹的需求,自动覆盖目标路径的同名文件 - 去掉了硬等待逻辑:不再靠固定时长的sleep判断任务完成,不管资源包多大,都会等实际操作完成再继续,无无效等待
内容的提问来源于stack exchange,提问作者Ali
相关产品推荐
相关产品推荐

