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

我正在尝试使这个脚本工作.它是一个 Bash脚本,用于获取一些变量,将它们放在一起并使用结果发送 AppleScript命令.手动粘贴从osascript -e后面的变量to_osa回显到终端的字符串按照我的意愿工作并期望它.但是当我尝试将命令osascript -e和字符串to_osa结合起来时,它不起作用.我怎样才能做到这一点?
the_url="\"https://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
作为一般规则,不要在变量中加入双引号,将它们放在变量周围.在这种情况下,它更复杂,因为你有一些用于bash级引用的双引号,还有一些用于AppleScript级引用;在这种情况下,AppleScript级引号放在变量中,bash级引号围绕变量:
the_url="\"https://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在通过bash解析(引用和转义删除等)之后打印它的参数,但是当你说“手动粘贴字符串……工作”时你会说它是你想要的解析之前.如果回显字符串中有引号,则表示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

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...