Create Context Menu Items in Mac Finder
As much as I like exercising my command line skills, for many tasks I'd rather click a time or two. The problem is that
brew install, and other package managers don't come with UI extending capabilities...so knowledgable people like us need to find a way to shoehorn those functionality into a UI. That UI on Mac is Automator; let's explore how we can add custom context menu items within macOS Finder!
Creating a Context Menu Item with Automator
The example we'll use is creating a context menu to unrar
rar archives. The following steps will have you on your way to adding a context menu within macOS Finder:
- Open Applications -> Automator
- File -> New in the menu bar
- Chose a document type of Service
- Within the right pane's top panel, choose files or folders from the first dropdown and then Finder.app from the second dropdown.
- Within the left actions pane, select Run Shell Script
- When the Run Shell Script box appears in the right pane, change the Pass input value to to arguments.
- Now you can write whatever shell scripting you'd like, receiving the file arguments as
$@. My script to unrar'ing files is overly simple:
# Enter the first file's directory current_path=$(dirname "$1") cd "$current_path" # For every file, unrar it to the current directory for f in "$@" do /usr/local/bin/unrar x "$f" done # Exit 0 so annoying errors don't popup exit 0
You can add additional checks to ensure the file is of the correct extension and other validation using a bit more scripting.
- File -> Save in the menu bar to save the Automator task. The name you save the task as is what will display as the context menu name.
Debugging and Testing the Context Menu Item
The best method for testing and debugging an Automator task is by adding additional actions to the task to simulate real usage. In our case, adding a Get Specified Finder Items action allows us to choose a valid file and test the outcome of the action:
Automator provides error and success messages in when running tasks, a luxury that using the context menu may not provide you. When you're satisfied that your Automator task is working properly, delete any temporary debugging actions you created.
Using the Context Menu Item
Right-click any files or folders in Finder (in our case, just
.rar files) and choose Services -> (Your Task Name Here):
Your task will execute in the background.
While I pride myself on improving my command line skills, I wish I had researched Automator task creation years ago. Downloading a file to finder and then jumping over to command line is sometimes inconvenient -- sometimes it's just nice to perform a few clicks instead of remembering commands and argument formats.