Reputation: 89
I need to use the Apple choose file dialog to select a file to use in a bash script. I believe the only way to do this is in AppleScript. I would like to call an AppleScript from within bash, and have it return the location of the selected file as a variable to be used in the shell script. So far I have:
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
How do I now pass the location of the PDF - the AppleScript variable PDFName
- back to the Shell?
Upvotes: 1
Views: 1153
Reputation: 6092
Here's a modified version of your script:
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
)
The changes to note are:
tell application
...end tell
statements, which are unnecessary;file
object specifier and the coercion to alias
, as the choose file
command returns a file alias
object by default;" com.adobe.pdf"
to allow PDF files to be selectable;set PDFName to the POSIX path of thePDF
;osascript
to a bash variable using thePDF=$(...)
.The osascript
returns the full posix path to the file, e.g. /Users/CK/Documents/somefile.pdf
, which is now assigned to the bash variable $thePDF
.
If you happen to get a warning about /System/Library/PrivateFrameworks/FinderKit.framework/Versions/A/FinderKit
, this can be ignored and silenced by making the following small edit: osascript 2>/dev/null <<EOF
.
Upvotes: 3
Reputation: 36
You can send text generated within osascript to stdout and catch it, e.g., in a variable. Like so:
#!/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"
Here, the whole osascript bit gets executed as "command substitution" (see bash man page), where the expression between $( ... ) is replaced by the result of the execution of that expression.
Key here is of course the AppleScript line "copy ... to stdout" above.
Alternatively, you could pipe the output of the osascript to the next command by
osascript <<EOF
(your code here)
copy output to stdout
EOF | next_command
Upvotes: 0