You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Bash脚本中嵌入AppleScript实现Dock程序驻坞失败排查

问题描述

我有一段可正常运行的AppleScript,能将指定应用固定到Dock:

set theAppPath to "/Applications/Adobe Acrobat Reader.app"
try
    set theShellScript to "defaults write com.apple.dock persistent-apps -array-add '<dict><key>tile-data</key><dict><key>file-data</key><dict><key>_CFURLString</key><string>" & theAppPath & "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>'"
    do shell script theShellScript
    do shell script "killall -HUP Dock"
end try

但将这段代码通过osascript嵌入到Bash脚本中执行时却毫无效果,我的Bash脚本如下:

#!/bin/bash
#!/usr/bin/env osascript
osascript <<EOD
set theAppPath to "/Applications/Adobe Acrobat Reader.app"
try
    set theShellScript to "defaults write com.apple.dock persistent-apps -array-add '<dict><key>tile-data</key><dict><key>file-data</key><dict><key>_CFURLString</key><string>" & theAppPath & "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>'"
    do shell script theShellScript
    do shell script "killall -HUP Dock"
end try
EOD
exit 0

同一个Bash脚本里的另一段osascript嵌入代码(创建快捷方式)能正常运行,但这段固定Dock的代码就是不行。我更希望直接嵌入实现,而非调用外部.scpt文件。另外,理想状态下希望在Bash脚本的osascript部分用$APP_PATH变量替代AppleScript里的theAppPath。

系统环境:macOS 15,单独运行这段AppleScript是有效的,尝试过多种osascript调用方式均无效。

解决步骤

1. 移除无效的Shebang行

Bash脚本里的#!/usr/bin/env osascript完全多余,还会干扰脚本执行——Bash脚本只需要开头的#!/bin/bash即可,直接删除这一行。

2. 修复字符串转义冲突问题

嵌入的AppleScript中,do shell script里的单引号会和Bash的Here Document(<<EOD)解析规则冲突,导致命令执行异常。把AppleScript里包裹plist字典的单引号替换为转义双引号(\")即可解决:

set theShellScript to "defaults write com.apple.dock persistent-apps -array-add \"<dict><key>tile-data</key><dict><key>file-data</key><dict><key>_CFURLString</key><string>" & theAppPath & "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\""

3. 实现Bash变量传递到AppleScript(推荐方案)

用osascript的参数传递机制,能避免转义问题,同时安全复用Bash变量。具体做法是在AppleScript中通过on run argv接收参数,再从argv列表中取出Bash传入的$APP_PATH:

完整可运行的Bash脚本

#!/bin/bash
# 定义要固定到Dock的应用路径
APP_PATH="/Applications/Adobe Acrobat Reader.app"

# 嵌入AppleScript并传递Bash变量
osascript - "$APP_PATH" <<'EOD'
on run argv
    set theAppPath to item 1 of argv
    try
        # 用转义双引号包裹plist字典,避免解析冲突
        set theShellScript to "defaults write com.apple.dock persistent-apps -array-add \"<dict><key>tile-data</key><dict><key>file-data</key><dict><key>_CFURLString</key><string>" & theAppPath & "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\""
        do shell script theShellScript
        # 重启Dock让修改生效
        do shell script "killall -HUP Dock"
    end try
end run
EOD

exit 0

内容的提问来源于stack exchange,提问作者Daniel T.S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 19:52:48