How do you close a file that you've opened with /usr/bin/open?

Solution 1:

You can't, at least not directly. /usr/bin/open will have told some other app to open the file, and then immediately dissociated itself from the whole affair.

If you know which app did the actual open, you might be able to use scripting to tell the app to close it. Something like

/usr/bin/open SomeFile.pdf
# time passes
/usr/bin/osascript -e 'tell application "Preview" to close document "SomeFile.pdf"'

But that pre-supposes that you know Preview is the app, and that this is the correct syntax for telling it to close a document, and that you've gotten the correct value for the document's name.

You can eliminate some of that uncertainty by specifying the app in the open command, and by assuming that the document will still be the front document when your script wants to close it.

/usr/bin/open -a Preview SomeFile.pdf
# do some stuff
/usr/bin/osascript -e 'tell application "Preview" to close front document'

(It might be more robust to refer to the app by its bundle-id rather than name

/usr/bin/open -b com.apple.Preview SomeFile.pdf
# do some stuff
/user/bin/osascript -e 'tell application id "com.apple.Preview" to close front document

but that's barely more than a matter of style.)

In general, /usr/bin/open can open just about anything. It behaves like double-clicking, so it can "open" windows (in Finder), applications (as themselves), disk images (by mounting them), network shares (by connecting to them), or even ordinary documents (by launching the app currently selected as the default app for that document type). Each of these flavors of "open" has its own flavor of "close".