osascript如何传入一个变量

osascript how to pass in a variable

我有以下,不工作。它在终端中打开一个新选项卡,但未传入变量 $DomainName?

DomainName="example.com"
osascript -e 'tell application "Terminal" to do script "watch dig +short NS $DomainName"'

结果是:

watch dig +short NS $DomainName

如何传入变量?

OP 的问题是在调用 osascript.

时如何 [不] 清理 shell 脚本输入的大师班

这是非常不安全的:

foo="DO NOT DO THIS; say bad script"
osascript -e "tell application \"Terminal\" to do script \"echo $foo\""

(运行 这个例子明白我的意思,然后考虑一个不太友好的字符串会造成什么。)

双引号变量 $foo 作为 "$foo" 可以安全地通过顶级 shell 脚本。它 NOT 通过 AppleScript 安全获取它:

foo="say \"bad script\""
osascript -e "tell application \"Terminal\" to do script \"echo $foo\""

如果你运行那个例子,它会失败并出现 AppleScript 编译错误:标识符不能跟在这个“”之后。(-2740)

那是因为osascript收到了字符串:

tell application "Terminal" to do script "echo say "bad script""

这是无效的语法。 (尝试在脚本编辑器中编译该行以查看。)

传递 AppleScript 参数的正确方法是将它们附加到 osascript 的参数列表中:

osascript -ss -e "…" - "arg1" "arg2" "arg3"

需要 - 分隔符来将命令自己的选项列表与要转发给 AppleScript 的 run 处理程序的其余参数分开。

顺便说一句,通过 osascript 的标准输入而不是 -e 选项传递 AppleScript 也是一个好主意,因为这样您就可以编写普通的 AppleScript 代码而不必转义它:

osascript -ss - "arg1" "arg2" "arg3" <<EOF

    on run argv -- argv is a list of 3 strings
        argv -- do stuff with argv here
    end run

EOF

(您可以安全地 运行 该示例:它只是将 argv 的值写入标准输出。)

好的,就向 AppleScript 传递参数而言,这是安全的。

..

但是,OP 的 AppleScript 在 Terminal.app 中创建了一个新的 shell 脚本 运行。因此, 必须清理用于构建 shell 脚本的 AppleScript 字符串,这是使用 AppleScript 的 quoted form of STRING 属性.

所以这是正确的安全方法来通过所有三个级别的代码生成来清理任意字符串:

bar='$test" \t#est*;say bad script' # a proper nasty test string

osascript -  "$bar"  <<EOF

    on run argv -- argv is a list of strings
        tell application "Terminal"
            do script ("echo " & quoted form of item 1 of argv)
        end tell
    end run

EOF

运行 那个例子,我在这里使用的相当可怕的测试字符串一直安全地传递到 echo

是的,所有这些字符串 sanitization/code 生成的东西 令人头疼的,但这就是你使用这么多由疯狂的人设计的语言所得到的结果。