8 macos bash applescript osascript
我正在尝试使这个脚本工作.它是一个Bash脚本,用于获取一些变量,将它们放在一起并使用结果发送AppleScript命令.手动粘贴从to_osa后面的变量回显osascript -e到终端的字符串按我的意愿工作并期望它.但是当我尝试将命令osascript -e和字符串组合在一起时to_osa,它不起作用.我怎样才能做到这一点?
the_url="\"http://stackoverflow.com/questions/1521462/looping-through-the-content-of-a-file-in-bash\""
the_script='tell application "Safari" to set the URL of the front document to '
delimiter="'"
to_osa=${delimiter}${the_script}${the_url}${delimiter}
echo ${to_osa}
osascript -e ${to_osa}
Run Code Online (Sandbox Code Playgroud)
除了手动工作之外,当我将所需命令写入脚本然后执行它时,脚本也可以工作:
echo "osascript -e" $to_osa > ~/Desktop/outputfile.sh
sh ~/Desktop/outputfile.sh
Run Code Online (Sandbox Code Playgroud)
foo*_*foo 12
字符串mashing可执行代码容易出错且很邪恶,这里绝对不需要它.通过定义显式的"运行"处理程序将参数传递给AppleScript是微不足道的:
on run argv -- argv is a list of strings
-- do stuff here
end run
Run Code Online (Sandbox Code Playgroud)
你然后调用它:
osascript -e /path/to/script arg1 arg2 ...
Run Code Online (Sandbox Code Playgroud)
顺便说一句,如果你的脚本需要固定数量的args,你也可以这样写:
on run {arg1, arg2, ...} -- each arg is a string
-- do stuff here
end run
Run Code Online (Sandbox Code Playgroud)
...
更进一步,您甚至可以像使用任何其他shell脚本一样使AppleScript直接执行.首先,添加一个hashbang,如下所示:
#!/usr/bin/osascript
on run argv
-- do stuff here
end run
Run Code Online (Sandbox Code Playgroud)
然后以未编译的纯文本格式保存并运行chmod +x /path/to/myscript以使文件可执行.然后,您可以从shell执行它,如下所示:
/path/to/myscript arg1 arg2 ...
Run Code Online (Sandbox Code Playgroud)
或者,如果您不想每次都指定完整路径,请将文件/usr/local/bin放在shell的PATH上或其他目录中:
myscript arg1 arg2 ...
Run Code Online (Sandbox Code Playgroud)
...
所以这就是你应该如何编写原始脚本:
#!/bin/sh
the_url="http://stackoverflow.com/questions/1521462/looping-through-the-content-of-a-file-in-bash"
osascript -e 'on run {theURL}' -e 'tell application "Safari" to set URL of document 1 to theURL' -e 'end run' $the_url
Run Code Online (Sandbox Code Playgroud)
快速,简单,非常强大.
-
ps如果您想在新窗口而不是现有窗口中打开URL,请参阅OS X open工具的联机帮助页.
作为一般规则,不要在变量中放置双引号,而是将它们放在变量周围。在这种情况下,情况会更复杂,因为您有一些用于 bash 级引用的双引号,还有一些用于 AppleScript 级引用;在这种情况下,AppleScript 级别的引号位于变量中,bash 级别的引号位于变量周围:
the_url="\"http://stackoverflow.com/questions/1521462/looping-through-the-content-of-a-file-in-bash\""
the_script='tell application "Safari" to set the URL of the front document to '
osascript -e "${the_script}${the_url}"
Run Code Online (Sandbox Code Playgroud)
顺便说一句,使用echo这样的方法来检查是非常具有误导性的。echo是告诉您变量中的内容,而不是当您在命令行上引用该变量时将执行的内容。最大的区别是,在经过 bash 解析(引用和转义删除等)后echo打印其参数,但是当你说“手动粘贴字符串......有效”时,你是说这就是解析之前你想要的。如果回显字符串中存在引号,则意味着 bash 无法将它们识别为引号并将其删除。比较:
string='"quoted string"'
echo $string # prints the string with double-quotes around it because bash doesnt't recognize them in a variable
echo "quoted string" # prints *without* quotes because bash recognizes and removes them
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4463 次 |
| 最近记录: |