applescript 通过 do shell script 调用 defaults 命令读写 macos 系统偏好设置,需组合读取、写入、重载与校验四环节:用 defaults read 获取键值,defaults write 写入后 killall 重载进程,写入前比对当前值避免重复,关键设置需辅助功能授权,并可调用 system preferences 直接跳转对应面板。

AppleScript 本身不直接读写 macOS 的系统偏好设置,但能通过 do shell script 安全调用 defaults 命令完成变更,关键在于组合读取、写入、重载与校验四个环节。
读取当前偏好设置值
使用 defaults read 获取任意 domain(如 NSGlobalDomain、com.apple.finder)下的键值。路径需转为 POSIX 格式,且应包裹在 try 块中防错:
- 检查 Finder 是否显示隐藏文件:
do shell script "defaults read com.apple.finder AppleShowAllFiles" - 读取全局键盘重复延迟:
do shell script "defaults read NSGlobalDomain KeyRepeat" - 若键不存在或权限不足,脚本会报错,建议提示用户“该设置未配置”或“需重启应用生效”
写入并使设置立即生效
仅写入不重载,GUI 应用无法感知变更。常见做法是 defaults write 后紧跟 killall:
- 启用 Dock 自动隐藏:
do shell script "defaults write com.apple.dock autohide -bool true && killall Dock" - 关闭 Finder 标题栏阴影:
do shell script "defaults write com.apple.finder DisableShadow -bool true && killall Finder" - 部分设置(如屏幕保护密码)还需额外执行
killall cfprefsd刷新偏好服务
避免重复写入与权限问题
多次写入可能引发异常,应在写入前比对当前值:
- 先读取:
set currVal to do shell script "defaults read com.apple.screensaver idleTime 2>/dev/null || echo 0" - 仅当不等于目标值时才写入:
if currVal is "0" then do shell script "defaults write com.apple.screensaver idleTime -int 600" - 涉及辅助功能(如
com.apple.universalaccess)时,需用户已授权“辅助功能”权限,否则defaults write可能静默失败
联动系统偏好设置界面辅助确认
AppleScript 可直接打开对应设置面板,方便用户核对或手动调整:
- 跳转到“安全性与隐私”→“隐私”→“辅助功能”:
tell application "System Preferences" to reveal pane "com.apple.preference.security" - 打开“键盘”偏好设置:
tell application "System Preferences" to reveal pane "com.apple.preference.keyboard" - 配合
activate确保窗口前置,提升操作连贯性











