繁体   English   中英

在applescript和shell脚本之间传递参数

[英]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
)

需要注意的变化是:

  1. 删除tell application ... end tell语句,这是不必要的;
  2. 因此删除file对象说明符和强制alias ,因为choose file命令默认返回文件alias对象;
  3. 消除" com.adobe.pdf"的空间以允许选择PDF文件;
  4. 将AppleScript代码的倒数第二行更改为: set PDFName to the POSIX path of thePDF ;
  5. 分配的输出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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM