osascript: select multiple files & print new-line delimited POSIX

In a shell script I’m trying to use osascript to have the user select one or several files, while returning the results (the choices) as POSIX paths, each path on a new line. I have only gotten one step of the way, in that it works with a single selected file, but as soon as I select several files, I get an error message:

(Note 1: the variable $lastpath is a placeholder and will eventually be defined by defaults reading from a preferences file; note 2: there will eventually be a “2>/dev/null” after “osascript”.)

lastpath="$HOME/Documents"
pathchoice=$(osascript << EOT
tell application "System Events"
	activate
	set theDir to "$lastpath"
	set theAliasPaths to (choose file with prompt "Please select files or applications for the operation…" default location theDir with invisibles and multiple selections allowed) as alias
	set thePOSIXPaths to (the POSIX path of theAliasPaths)
end tell
EOT
)
echo "$pathchoice"

I assume that since I have a bunch of selected files, AppleScript/osascript would have to go through every one consecutively, convert their alias path to POSIX path, and write that to a new table, and print that once finished.

Anyone with an idea? Thank you in advance.

  1. Command choose file returns alias files, so command as alias at the end no need
  2. No need osascript:

set documents_Path to path to documents folder
set theAliasPaths to (choose file with prompt "Please select files or applications for the operation…" default location documents_Path with invisibles and multiple selections allowed)

set myMessage to ""
set myList to {}
repeat with theAliasFile in theAliasPaths
	tell application "System Events" to set thePosixPash to POSIX path of theAliasFile
	set end of myList to thePosixPash
	set myMessage to myMessage & thePosixPash & return
end repeat
-- myList -- delete first "--" to see the resulting list instead of myMessage

Thank you, it worked.

I’m dropping myMessage completely in favor of myList. In the shell script, I simply create the line breaks after-the-fact with:

filepaths=$(echo “$filepaths” | sed ‘s-, /-\n/-g’)

By the way, that’s why osascript is needed in my case. I’m running the AppleScript part from within a bash shell script, and that can only be done with the osascript CLI.

One addition: if you want to do it all within AppleScript, I found out that you need to use

set myMessage to myMessage & thePosixPash & return & linefeed

If you don’t use " & linefeed", the filepaths will become garbled/merged.

The shell is expecting linefeeds. But you would use linefeeds instead of returns, not as well.

You’re right: I was getting errors from the shell script, in that the paths printed by osascript did not exist. As soon as I removed the " & return", everything was working.