#ios osascript 是 macOS 系统自带的 AppleScript 和 JavaScript 解释器,主要用于通过命令行执行自动化脚本操作。以下是关键信息: ### 核心功能 1. 执行 AppleScript ``` shell # 弹出对话框 osascript -e 'display dialog "Hello macOS"' ``` 2. 运行 JavaScript (JXA) ``` shell # 使用 JavaScript 操作 Finder osascript -l JavaScript -e 'Application("Finder").emptyTrash()' ``` 3. 脚本文件执行 ``` shell osascript /path/to/script.scpt ``` ### 典型应用场景 ``` | 场景 | 示例命令 | |---------------------|--------------------------------------------------------------------------| | 系统控制 | osascript -e 'tell app "System Events" to shut down' | | 应用自动化 | osascript -e 'tell app "Safari" to open location "https://example.com"'| | 文件操作 | osascript -e 'tell app "Finder" to delete file "test.txt"' | | 数据交换 | osascript -e 'text returned of (display dialog "输入内容" default answer "")' | ``` ### 高级用法 1. 传递参数 ``` shell osascript -e 'on run argv' -e 'return item 1 of argv' -e 'end run' -- "参数" ``` 2. 获取返回值 ``` shell result=$(osascript -e 'return "输出内容"') echo $result # 输出:输出内容 ``` 3. 与 Shell 脚本集成 ``` shell # 获取当前WiFi名称 wifi_name=$(osascript -e 'do shell script "networksetup -getairportnetwork en0 | cut -c 24-"') ``` ### 安全限制 - macOS 10.15+ 需要授权: 系统偏好设置 → 安全性与隐私 → 自动化 !自动化权限设置 - 敏感操作需终端授权: ``` shell # 首次执行会弹出权限请求 osascript -e 'tell app "Terminal" to do script "echo hello"' ``` ### 性能对比 | 脚本类型 | 启动时间 | 内存占用 | 适用场景 | |--------------|----------|----------|-----------------------| | AppleScript | 快 | 低 | 系统级自动化 | | JavaScript | 中 | 中 | 复杂数据处理 | | Python | 慢 | 高 | 跨平台/复杂逻辑 | --- ### 替代方案 - Swift 脚本:性能更好,但学习成本高 - Python/Ruby:跨平台但需要环境配置 - Automator:图形化操作但灵活性低 建议:需要深度 macOS 集成时优先使用 osascript,跨平台需求则选择其他语言。