MacOS – launch the File (Save/Open) Dialog from the command line

automatorcommand linefindermacosterminal

Bash and vim's file completion facilities are effective for navigating through a few levels of a directory structure, but can be cumbersome when working with unfamiliar directories. Alternatively, I use a fuzzy search plugin in vim, which is effective within a project, but less so across the full drive.

What I'd like to use in these situations is the osx file browser dialog. I imagine this would be accomplished via the "Save As…" or "Open…" dialogs. Is there any way to launch one of these dialogs from the command line and have it write the selection to stdout?

I found this question about displaying alerts. The answers are focused on using Automator. Can we use a similar approach to achieve my goal?

Worst-case scenario, I imagine it wouldn't be too difficult to build, but I've been focused on web programming for the last 10 years or so. Could someone point me in the direction of some relevant resources? I imagine I'd need to build a native osx app in objective-c or Swift using Cocoa?

Best Answer

This can be done using AppleScript, like in the question you linked to. Watch out, this is not the same as Automator.

Example script:

osascript -e 'tell application (path to frontmost application as text)
set myFile to choose file
POSIX path of myFile
end'

This uses the simplest form of the choose file command, and puts the result in the variable myFile. The result will be of type alias, which has a POSIX path property, which we read in the next line. The result will be written to stdout.

Look here for all the possible optional options to the choose file command. You can e.g. provide a custom prompt text, choose a default location, or only allow certain file types.