我需要使用Apple选择文件对话框来选择要在bash脚本中使用的文件。我相信做到这一点的唯一方法是在AppleScript中。我想从bash中调用AppleScript,并让它返回所选文件的位置作为要在Shell脚本中使用的变量。到目前为止,我有:
public class ListAdptot extends ArrayAdapter<pdf> {
List<pdf> pdffile;
String m_Text;
//activity context
Context context;
//the layout resource file for the list items
int resource;
//constructor initializing the values
public ListAdptot(Context context, int resource, List<pdf> pdfList) {
super(context, resource, pdfList);
this.context = context;
this.resource = resource;
this.heroList = pdfList;
}
@NonNull
@Override
public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(resource, null, false);
Typeface custom_font = Typeface.createFromAsset(getContext().getAssets(),"DroidSans-Bold.ttf");
TextView textViewName = view.findViewById(R.id.title);
ImageButton download=view.findViewById(R.id.download);
textViewName.setTypeface(custom_font);
pdf PDF= pdffile.get(position);
textViewName.setText(pdf.getName());
download.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//What i can do here.
}
});
return view;
}
}
现在如何将PDF(AppleScript变量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
)的位置传递回Shell?
答案 0 :(得分:3)
这是脚本的修改版本:
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
将thePDF=$(...)
的输出分配给bash变量。 osascript
返回文件的完整posix路径,例如/Users/CK/Documents/somefile.pdf
,现在已将其分配给bash变量$thePDF
。
如果您碰巧收到关于/System/Library/PrivateFrameworks/FinderKit.framework/Versions/A/FinderKit
的警告,可以通过以下较小的编辑操作osascript 2>/dev/null <<EOF
将其忽略并消除。
答案 1 :(得分:0)
您可以将在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 stdout”。
或者,您可以通过以下方式将osascript的输出传递给下一个命令:
osascript <<EOF
(your code here)
copy output to stdout
EOF | next_command