[英]passing parameters between applescript and shell script
我需要使用Apple選擇文件對話框來選擇要在bash腳本中使用的文件。 我相信唯一的方法是使用AppleScript。 我想從bash中調用AppleScript,並讓它將所選文件的位置作為要在shell腳本中使用的變量返回。 到目前為止,我有:
osascript <<EOF
tell Application "Finder"
set strPath to "/my/default/location/"
set thePDF to file (choose file with prompt "Choose a PDF: " of type { " com.adobe.pdf" , "dyn.agk8ywvdegy" } without invisibles default location strPath) as alias
set PDFName to name of file thePDF
end tell
EOF
我現在如何將PDF的位置 - AppleScript變量PDFName
- PDFName
回Shell?
這是您腳本的修改版本:
thePDF=$(osascript <<EOF
set strPath to "/my/default/location/"
set thePDF to (choose file with prompt ("Choose a PDF: ") ¬
of type {"com.adobe.pdf", "dyn.agk8ywvdegy"} ¬
default location strPath ¬
without invisibles)
set PDFName to the POSIX path of thePDF
EOF
)
需要注意的變化是:
tell application
... end tell
語句,這是不必要的; file
對象說明符和強制alias
,因為choose file
命令默認返回文件alias
對象; " com.adobe.pdf"
的空間以允許選擇PDF文件; set PDFName to the POSIX path of thePDF
; osascript
使用一個bash變量thePDF=$(...)
osascript
返回文件的完整posix路徑,例如/Users/CK/Documents/somefile.pdf
,現在分配給bash變量$thePDF
。
如果您碰巧收到關於/System/Library/PrivateFrameworks/FinderKit.framework/Versions/A/FinderKit
的警告,可以通過進行以下小編輯來忽略和靜音: osascript 2>/dev/null <<EOF
。
您可以將osascript中生成的文本發送到stdout並捕獲它,例如,在變量中。 像這樣:
#!/bin/bash
PDFNAME=$( osascript <<EOF
tell Application "Finder"
set strPath to "/your/pdf/path/"
set thePDF to file (choose file with prompt "Choose a PDF: " without invisibles default location strPath) as alias
set PDFName to name of file thePDF
end tell
copy PDFName to stdout
EOF )
echo "From bash: $PDFNAME"
這里,整個osascript位被執行為“命令替換”(參見bash手冊頁),其中$(...)之間的表達式被該表達式的執行結果替換。
這里的關鍵當然是上面的AppleScript行“copy to to stdout”。
或者,您可以將osascript的輸出通過管道傳遞給下一個命令
osascript <<EOF
(your code here)
copy output to stdout
EOF | next_command
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.