我遇到了在 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。
I'm sure I'm missing something simple. I've looked all over google and stack overflow but all the examples are for only one variable.
uj5u.com熱心網友回復:
你說:
“我基本上想在選擇取消按鈕時退出整個腳本,但我似乎無法同時輸入文本和按下哪個按鈕。”
首先,在用戶單擊“取消”按鈕的情況下,不可能同時回傳輸入的文本和按下的按鈕。這僅僅是因為取消對話框時 AppleScript 會產生-128您提到的錯誤。
考慮通過使用以下 shell 腳本來采取不同的方法。1如果用戶選擇“取消”按鈕,它本質上會以退出代碼提前退出 bash 腳本。但是,當單擊“確定”按鈕時,輸入的任何文本(即用戶名)都會分配給username變數。
#!/usr/bin/env bash
if ! username=$(osascript 2> /dev/null <<-EOF
return text returned of (display dialog "Enter your name" with title ?
"Question" default answer "" buttons {"Cancel", "Rename"} default button "Rename")
EOF
); then
exit 1
fi
# Continue to do something with $username...
echo "$username"
解釋
$(...)部分(命令替換)用于將命令的結果分配給osascript變數username。該
2> /dev/null部分重定向stderr到/dev/null. 當用戶單擊“取消”按鈕時,這基本上可以防止 AppleScript-128錯誤訊息被列印到控制臺。該
<<-EOF部分(此處檔案)用于將 AppleScript 代碼傳遞給osascript命令。在將多行代碼(本例中為 AppleScript)傳遞給 shell 時,使用 Here 檔案特別有用。條件
if陳述句以撇號(一個!運算式)開頭,如果運算式為假,則表示為真。本質上,在這種情況下,這意味著如果osascript命令的結果為假(即用戶單擊了“取消”),則執行該exit 1陳述句。
附加說明:
上述示例代碼在 macOS Monterey (12.2.1)上成功運行,但是在 OSX 上的某些舊版本上,您可能需要包含 AppleScript“系統事件”tell塊和activate陳述句。當我在運行 OSX (10.6.8)的舊機器上測驗腳本(上圖)時,沒有它們就不會出現對話框。例如,您可能需要執行以下在 OSX (10.6.8)上成功運行的操作:
#!/usr/bin/env bash
if ! username=$(osascript 2> /dev/null <<-EOF
tell application "System Events"
activate
return text returned of (display dialog "Enter your name" with title ?
"Question" default answer "" buttons {"Cancel", "Rename"} default button "Rename")
end tell
EOF
); then
exit 1
fi
# Continue to do something with $username...
echo "$username"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/434634.html
標籤:bash applescript
上一篇:排隊多個子行程
