我遇到了在 AppleScript 和 bash 之间传递多个变量的问题。
我可以用这样的方法得到一个变量
updatedName="$(osascript -e 'set the answer to text returned of (display dialog "What is your name" with title "Question" default answer buttons {"Cancel", "Save"} default button "Save")' return answer)"
我如何获得文本的答案以及选择了哪个按钮?我基本上想在选择取消按钮时退出整个脚本,但我似乎无法同时输入文本和按下哪个按钮。
我试过这样的事情,但取消按钮返回“26:246:执行错误:用户取消。(-128)”而不是 if 语句的退出 0。
question="$(osascript -e 'set theResultReturned to (display dialog "Enter your nane" with title "Question" default answer "" buttons {"Cancel", "Rename"} default button "Rename")' return answer)
set theTextReturned to the text returned of theResultReturned
set theButtonReturned to the button returned of theResultReturned
if theButtonReturned is "Cancel" then
exit 0
end if" || exit
我也试过在问题脚本后添加一个额外的 if 语句,但我也无法让它工作。
if [ "$question" = "theButtonReturned:Cancel" ];
then
exit 0
fi
如果我打印 $question 我得到一个完整的输出
button returned:Rename, text returned:Test
set theTextReturned to the text returned of theResultReturned
set theButtonReturned to the button returned of theResultReturned
if theButtonReturned is Cancel then
exit 0
end if
这给了我返回的文本和按钮输出,但随后它也打印出了整个 osascript。
我确定我错过了一些简单的东西。我在谷歌和 stack overflow 上都看过了,但所有的例子都只针对一个变量。
return answer
属于单独的一行;在你的第一行,你错过了""
afterdefault answer
; 最后,当使用 osascript 时,applescript 的每一行都应该得到一个-e
,而不仅仅是第一行。try
语句来处理错误,但我认为您仍然会在不知道用户在取消之前输入的内容的情况下结束tell
块(和)的原因activate
是出于历史原因。当我在运行 OSX (10.6.8)的旧机器上测试脚本时,如果没有它们,对话框不会出现。然而在 macOS Monterey (12.2.1)上运行它们实际上并不是必需的——只是这个简化的示例在 Monterey 上成功运行(......以及前面的示例也是如此)。本质上,因为我不知道在这种情况下使用的是哪个操作系统版本,所以我只是提供了在两个操作系统版本中都成功运行的代码/示例。