bash 和 applescript 的字符串文字

String literal with bash and applescript

这是基于以下问题的答案:

https://apple.stackexchange.com/questions/103565/bash-script-that-will-start-up-second-terminal-process

执行此 applescript 命令在终端中运行良好(它打开一个新的 window 并告诉我正常运行时间):

osascript -e 'tell app "Terminal" to do script "uptime"'

但是,尝试将变量作为字符串文字传递是行不通的:

cmd="'tell app \"Terminal\" to do script \"uptime\"'"
osascript -e ${cmd}

"0:1: 语法错误:此处不能输入未知标记。(-2740)"

怎么回事?

我无法真正解释为什么下面的代码有效,但它肯定与解析 shell 中的文本有关。 $cmd 周围的引号确保 space 被保留。 Osa 脚本本身不太喜欢撇号(单引号),所以我想这就是您的版本不起作用的原因。

你可以这样做:

 cmd="tell application \"Terminal\" to do script \"uptime\""
 osascript -e "$cmd"

至少这对我有用。 :)

通过 osascript 停止 teamviewer 的类似问题通过双重转义为我解决,以获得内部双引号。我没有使用单引号来允许 bash 扩展。

# TeamViewer
alias tvstop="sudo osascript -e \"quit app \\"TeamViewer.app\\"\""
alias tvstart="open -g -a /Applications/TeamViewer.app"