AppleScript在网络用户账号下同时执行If和Else分支的异常问题
问题
需求:为每个在客户端拥有本地用户文件夹的网络用户,在其登录时自动修改本地应用属性文件,具体操作如下:
- 检查文件中是否已存在指定修饰字符串
- 若不存在,则将该字符串追加到文本配置文件中
当前脚本在管理员账号运行完全正常:字符串已存在时显示调试对话框,不存在则追加字符串;但使用本地网络账号登录时,脚本会同时显示对话框并追加字符串,且每次登录都会重复追加,文件路径指向正确的配置文件。
脚本代码:
set userName to short user name of (system info) set JournalProps to "/Users/" & userName & "/NameOfTheConfigFileHere" close access (open for access JournalProps) set FontSize to "name_fontsize=18" set TheFileContents to paragraphs of (read JournalProps) if FontSize is in TheFileContents then set DisplayText to "Fontsize already set" display dialog DisplayText else write linefeed & "name_fontsize=18" & linefeed to JournalProps as "utf8" starting at eof end if
原因分析与修复方案
核心问题
- 文件访问逻辑漏洞:
close access (open for access JournalProps)这行代码有问题——如果文件原本没被打开,执行close access会触发错误,但AppleScript默认忽略错误继续跑,导致后续读取文件时可能拿到缓存的旧内容,甚至让文件处于异常状态,直接搞崩判断逻辑。 - 网络用户权限与文件状态不一致:网络账号对自身文件夹的文件权限可能有限制,加上网络文件系统的延迟,读取操作拿到的内容不是最新的,导致
FontSize is in TheFileContents始终返回false,但写入操作又能成功,就出现了弹窗和追加同时发生的矛盾情况。
修复后的脚本
set userName to short user name of (system info) set JournalProps to "/Users/" & userName & "/NameOfTheConfigFileHere" set FontSize to "name_fontsize=18" -- 安全处理文件访问流程 try set fileRef to open for access file JournalProps with write permission set TheFileContents to paragraphs of (read fileRef) if FontSize is in TheFileContents then set DisplayText to "Fontsize already set" display dialog DisplayText else write linefeed & FontSize & linefeed to fileRef as "utf8" starting at eof end if on error errMsg display dialog "处理配置文件出错:" & errMsg end try close access fileRef
关键改进点
- 用
try...on error捕获文件操作的异常,避免权限或访问错误导致逻辑混乱 - 统一通过文件引用
fileRef读写,确保文件状态一致,不会出现读旧内容写新内容的矛盾 - 明确指定
with write permission打开文件,适配网络用户的权限限制 - 复用
FontSize变量,避免硬编码重复内容
内容的提问来源于stack exchange,提问作者Simon Z
相关产品推荐
相关产品推荐

