I whipped up a script this morning to simulate Finder’s “Open With…” menu from the command line. It extends the macOS open command with a command line menu selection of apps able to open the file you specify.

This script uses the macOS commands mdfind and open, along with the third-party utilities duti and fzf or gum.

bash
find . -name '*.rb' | fzf | open-with

Produces:

I’m going to paywall this one as bonus content for my supporters. Join at any level to get the script.

[paywall]

Prerequisites

For the sake of keeping the script simple, I relied on a few third-party utilities, all of which can be installed with Homebrew.

This script is Mac-only, but will work with any version.

duti
A CLI for working with UTIs. It’s super handy if you haven’t already explored it.

[iterm command:”brew install duti” language:”bash”]

fzf or gum
These are great CLIs for presenting menus and other command line interactions (in the case of gum). I prefer fzf for this kind of script, and if you don’t specify one or the other when running this script, it will prefer fzf. If neither gum nor fzf are installed, you’ll get an error message.

[iterm command:”brew install fzf” language:”bash”]

[iterm command:”brew install gum” language:”bash”]

Installation

The script can be found in this gist.

Save the raw version of the script as open-with in your PATH and make it executable:

[iterm command:”chmod +x /path/to/open-script” language:”bash”]

Usage

console
Usage: open-with [OPTIONS] FILE
-l, --limit NUM Maximum number of apps to list
-g, --gui GUI Menu tool to use (fzf|gum, default auto-detect)
-h, --help Display this screen

The script will display a menu (fzf or gum) of all the apps that can open the file passed as an argument. Selecting an app opens the file in that app.

Use --limit N to limit to only the first N most likely apps for the file. Including a limit speeds up the command processing because it will only try to resolve N number of bundle ids to app paths. If it has to process all of the available apps it can take 5 or 6 seconds to respond. With a limit you can cut that down to 2 or 3 seconds.

Use --gui gum to override the automatic detection (fzf with gum fallback) and use gum.

The script alternatively accepts a single filename as input on STDIN, so you can pipe the results of another command to it:

[iterm command:”find . -type f fzf open-with -l 5 -g gum” language:”bash”]

Enjoy!

[/paywall]


Leave a Reply

Your email address will not be published. Required fields are marked *