Change the default application (for a file extension) via script/command line? Is there a way to define the default application for a file extension via an Apple script, command line command (like defaults write [...]).

I know that you can change it manually via the information panel or by using RCDefaultApp but as I have to setup many machines and user accounts I would like to find a way to automate the process.
Launch Services is responsible for default file associations.

Let's say I wanted to change all text files to open in Sublime Text 2.

First I need the kMDItemCFBundleIdentifier for Sublime Text 2. I can use mdls to get this information:

&gt; mdls /Applications/Sublime\ Text\ 2.app 
_kTimeMachineIsCreationMarker  = 1
_kTimeMachineNewestSnapshot    = 4001-01-01 00:00:00 +0000
_kTimeMachineOldestSnapshot    = 2012-02-22 03:49:19 +0000
kMDItemCFBundleIdentifier      = "com.sublimetext.2"
....snip....


I can find out the content type value for text files by inspecting one of them with mdls:

&gt; mdls test.txt 
kMDItemContentCreationDate     = 2012-03-25 04:18:50 +0000
kMDItemContentModificationDate = 2012-03-25 04:18:50 +0000
kMDItemContentType             = "public.plain-text"
kMDItemContentTypeTree         = (
    "public.plain-text",
    "public.text",
    "public.data",
    "public.item",
    "public.content"
)
kMDItemDateAdded               = 2012-03-25 04:18:50 +0000
kMDItemDisplayName             = "test.txt"
kMDItemFSContentChangeDate     = 2012-03-25 04:18:50 +0000
kMDItemFSCreationDate          = 2012-03-25 04:18:50 +0000
kMDItemFSCreatorCode           = ""
kMDItemFSFinderFlags           = 0
kMDItemFSHasCustomIcon         = 0
kMDItemFSInvisible             = 0
kMDItemFSIsExtensionHidden     = 0
kMDItemFSIsStationery          = 0
kMDItemFSLabel                 = 0
kMDItemFSName                  = "test.txt"
kMDItemFSNodeCount             = 975
kMDItemFSOwnerGroupID          = 20
kMDItemFSOwnerUserID           = 501
kMDItemFSSize                  = 975
kMDItemFSTypeCode              = ""
kMDItemKind                    = "Plain Text"
kMDItemLogicalSize             = 975
kMDItemPhysicalSize            = 4096


In this case I'll change the default application for all public.plain-text types.

To do this I type:

defaults write com.apple.LaunchServices LSHandlers -array-add '{ LSHandlerContentType = \"public.plain-text\"; LSHandlerRoleAll = \"com.sublimetext.2\"; }'


If I want the changes to take effect I'll need to restart Launch Services like so:

/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister -kill -r -domain local -domain system -domain user


And to give credit where credit is due, I learned about this approach from this stackoverflow.com question and answer: https://stackoverflow.com/questions/9172226/how-to-set-default-application-for-specific-file-types-in-mac-os-x