Changing the file association for a single file or a set of files (AppleScript)
This script demonstrates first that the default application for some text file on my system was set to TextEdit. Then it changes the file association for that particular file so it now opens with Atom. Finally, it associates all text files on the desktop with the Atom application.
tell application "System Events"
get the default application of the file "/path/to/some file.txt"
--> alias "Macintosh HD:Applications:TextEdit.app:" of application "System Events"
# Individual file:
set the default application of the file "/path/to/some file.txt" to ¬
the path to the application named "Atom"
# A set of files:
set the default application of every file of the desktop folder whose ¬
name extension = "txt" to the path to the application "Atom"
Changing the file associations for all files of a given type (JXA)
Here, I've targetted plain text files (these have extension
.txt by default), and switched the default application that responds to them to Atom:
var contentType = 'public.plain-text';
var bundleID = Application('Atom').id();
The file type must be targeted by way of a Uniform Type Identifier. These are special text strings that uniquely identify a given class or type of item. The link will take you to a page that lists Apple's system-declared UTIs for all the likely file types that you'll be interested in. Be careful not to simply choose the one that appears to match your needs at first glance, as UTIs are structured in a kind of inheritance tree. Therefore, I could have lazily picked out
public.text, which I saw first in the list, until on further reading, we learn that this UTI is a base type for all text, which would include