[英]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 脚本。 它不能安全地通过 AppleScript:
foo="say \"bad script\""
osascript -e "tell application \"Terminal\" to do script \"echo $foo\""
如果您运行该示例,它将失败并出现 AppleScript 编译错误:标识符不能在此“”之后 go。(-2740)
那是因为osascript
接收字符串:
tell application "Terminal" to do script "echo say "bad script""
这是无效的语法。 (尝试在脚本编辑器中编译该行以查看。)
通过 AppleScript arguments 的正确方法是将它们附加到osascript
的 arguments 列表:
osascript -ss -e "…" - "arg1" "arg2" "arg3"
需要-
分隔符将命令自己的选项列表与剩余的 arguments 分开以转发到 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
的值写入标准输出。)
好的,就将 arguments 传递给 AppleScript 而言,这是安全的。
..
但是,OP 的 AppleScript 创建了一个新的 shell 脚本以在 Terminal.app 中运行。 因此,还必须清理用于构造 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
。
是的,所有这些字符串清理/代码生成的东西都让人头疼,但这就是你使用这么多由疯狂的人设计的语言所得到的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.