如何遍历AppleScript中Terminal的settings set对象所有属性字段
遍历Terminal的settings set对象全字段(含AppleScript字典未收录属性)方法
验证前提
现有操作可证实Terminal的AppleScript字典存在未收录的有效字段:例如ShowActiveProcessArgumentsInTitle这个控制标题栏是否显示进程参数的plist属性可正常生效,但无对应的AppleScript关键字。可通过如下脚本切换到关闭该选项的「Red Sands」配置文件复现验证:
tell application "Terminal" set newTab to do script "bash /Users/jredfox/Desktop/hello.sh" set current settings of newTab to settings set "Red Sands" end tell
配套测试shell脚本hello.sh内容:
#!/bin/bash echo hello read -p "Press ENTER to continue..." exit
问题说明
已获取标签页对应的current settings of xtab对象(类型为settings set)时,无法直接通过repeat遍历该对象读取所有字段:一是对象本身不支持原生迭代,二是AppleScript字典未收录全部有效属性,直接读取声明属性会漏掉新增的隐藏字段。
实现方法
settings set对象本质是Terminal偏好设置plist中配置条目的映射,不需要依赖AppleScript字典暴露的属性,直接读取底层plist即可拿到全部字段:
- 第一步获取目标
settings set的唯一ID,Terminal所有配置都以该ID为key,存储在偏好设置文件的Window Settings节点下 - 第二步直接读取plist中对应ID下的全部键值,绕过AppleScript的对象属性解析层,就能拿到所有未被字典收录的隐藏字段
- 若需要修改未收录字段,直接写入plist对应键值后刷新配置即可生效
基础实现:读取全字段原始内容
tell application "Terminal" -- 替换为目标标签页对象,示例取最前窗口当前选中标签 set xtab to selected tab of front window set targetSettings to current settings of xtab set settingsID to id of targetSettings end tell -- 绕过AppleScript字典直接从偏好设置读取对应配置的全部内容 set allSettingsContent to do shell script "defaults read com.apple.Terminal 'Window Settings'." & quoted form of settingsID return allSettingsContent
进阶实现:获取可遍历的结构化键值对
如果需要逐个遍历处理字段,可通过System Events解析plist结构,直接拿到可迭代的属性列表:
tell application "Terminal" set xtab to selected tab of front window set targetSettings to current settings of xtab set settingsID to id of targetSettings end tell set plistPath to POSIX path of (path to preferences from user domain as text) & "com.apple.Terminal.plist" tell application "System Events" set terminalPlist to property list file plistPath set windowSettingsNode to property list item "Window Settings" of terminalPlist set targetConfigNode to property list item settingsID of windowSettingsNode -- allProps为可直接repeat遍历的属性集合,包含所有隐藏字段 set allProps to every property list item of targetConfigNode repeat with singleProp in allProps -- 此处可按需处理每个字段的名称和值 log (name of singleProp) & " = " & (value of singleProp) end repeat end tell
该方法读取到的字段和Terminal设置面板中实际生效的配置完全一致,不会出现字典缺漏字段的问题。
内容的提问来源于stack exchange,提问作者jredfox_
相关产品推荐
相关产品推荐

