Bash 在applescript和shell脚本之间传递参数
我需要使用Apple的“选择文件”对话框来选择要在bash脚本中使用的文件。我相信唯一的方法就是用AppleScript。我想从bash中调用AppleScript,并让它返回所选文件的位置,作为shell脚本中使用的变量。到目前为止,我已经:Bash 在applescript和shell脚本之间传递参数,bash,shell,applescript,Bash,Shell,Applescript,我需要使用Apple的“选择文件”对话框来选择要在bash脚本中使用的文件。我相信唯一的方法就是用AppleScript。我想从bash中调用AppleScript,并让它返回所选文件的位置,作为shell脚本中使用的变量。到目前为止,我已经: osascript <<EOF tell Application "Finder" set strPath to "/my/default/location/" set thePDF to file (
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)传递回Shell 您可以将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行副本。。。到上面去
或者,您可以通过以下方式将osascript的输出通过管道传输到下一个命令:
osascript <<EOF
(your code here)
copy output to stdout
EOF | next_command
以下是脚本的修改版本:
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应用程序…end tell语句;
因此,删除文件对象说明符和对alias的强制,因为choose file命令默认返回文件别名对象;
消除com.adobe.pdf中的空间,以允许选择pdf文件;
将AppleScript代码的倒数第二行更改为:将PDFName设置为PDF的POSIX路径;
使用thePDF=$…将osascript的输出分配给bash变量。。。。
osascript返回文件的完整posix路径,例如/Users/CK/Documents/somefile.pdf,该文件现在分配给bash变量$thePDF
如果您碰巧收到关于/System/Library/privateframes/FinderKit.framework/Versions/a/FinderKit的警告,则可以通过进行以下小编辑来忽略并消除此警告:osascript 2>/dev/null copy。。。顺便说一句,stdout实际上不是一件事。它恰好是脚本的最后一行,AppleScript将其作为结果返回。如果删除该行,脚本将返回相同的结果,因为它前面的行已设置为。。。,返回相同的结果。