在 Bash 中组合变量以形成使用 osascript 命令发送到 AppleScript 的命令

问题描述 投票:0回答:3

我正在努力让这个脚本发挥作用。这是一个 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}

除了手动工作之外,当我将所需的命令写入脚本然后执行它时,脚本也可以工作:

echo "osascript -e" $to_osa > ~/Desktop/outputfile.sh
sh  ~/Desktop/outputfile.sh
macos bash applescript osascript
3个回答
13
投票

字符串混搭可执行代码容易出错且邪恶,这里绝对不需要它。通过定义显式的“运行”处理程序将参数传递给 AppleScript 非常简单:

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

然后您可以像这样调用:

osascript -e /path/to/script arg1 arg2 ...

顺便说一句,如果你的脚本需要固定数量的参数,你也可以这样写:

on run {arg1, arg2, ...} -- each arg is a string
    -- do stuff here
end run

...

更进一步,您甚至可以像任何其他 shell 脚本一样直接执行 AppleScript。首先,添加一个hashbang,如下:

#!/usr/bin/osascript

on run argv
    -- do stuff here
end run

然后将其保存为未编译的纯文本格式并运行

chmod +x /path/to/myscript
以使文件可执行。然后您可以从 shell 执行它,如下所示:

/path/to/myscript arg1 arg2 ...

或者,如果您不想每次都指定完整路径,请将文件放入

/usr/local/bin
或 shell 路径上的其他目录中:

myscript arg1 arg2 ...

...

因此,您应该如何编写原始脚本:

#!/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

快速、简单且非常强大。

--

附注如果您想在新窗口而不是现有窗口中打开 URL,请参阅 OS X 的

open
工具的联机帮助页。


2
投票

作为一般规则,不要在变量中放置双引号,而是将它们放在变量周围。在这种情况下,情况会更复杂,因为您有一些用于 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}"

顺便说一句,使用 
echo

来检查这样的事情是非常具有误导性的。

echo
告诉您变量中的内容,而不是当您在命令行上引用变量时将执行的内容。最大的区别是
echo
打印其参数
after
他们已经通过 bash 解析(引用和转义删除等),但是当你说“手动粘贴字符串......有效”时,你说的是它是什么你想要 before 解析。如果回显字符串中存在引号,则意味着 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



0
投票

pathToRepo

是变量,

osascript
传递到打开的终端,然后
cd
进入正确的目录。 (然后运行
npm start
,如果您想添加更多命令,仅供参考)
pathToRepo="/Users/<YOUR_MAC_NAME>/Documents/<REPO_NAME>"

osascript - "$pathToRepo" <<EOF
    on run argv -- argv is a list of strings
        tell application "Terminal"
            do script ("cd " & quoted form of item 1 of argv & " && npm start")
        end tell
    end run
EOF

来源/参考:
https://stackoverflow.com/a/67413043/6217734

© www.soinside.com 2019 - 2024. All rights reserved.