A O
A O

Reputation: 5698

How to create a script that can edit a plist in OSX

So I am constantly manually modifying plists on a day-to-day basis (I'm on OSX 10.9), and I decided to create a script that will do this automatically for me.

After some more research, I found I could create a .command file to execute commands on a double clickable file.

Now, I'm not sure how I want to do the checking of a plist for a string, and if it's found, how to replace it. Any recommendations?

Thanks in advance!

Upvotes: 2

Views: 776

Answers (1)

Gordon Davisson
Gordon Davisson

Reputation: 126048

There are two relevant commands here: defaults and /usr/libexec/PlistBuddy. defaults is really set up for managing preference settings, while PlistBuddy is a more general plist tool. For instance, to check and set your dock orientation (which side of the screen it appears on), you could use:

oldOrientation=$(defaults read com.apple.dock orientation)
defaults write com.apple.dock orientation "$newOrientation"

vs. the PlistBuddy version:

oldOrientation=$(/usr/libexec/PlistBuddy -c "print :orientation" ~/Library/Preferences/com.apple.dock.plist)
/usr/libexec/PlistBuddy -c "set :orientation '$newOrientation'" ~/Library/Preferences/com.apple.dock.plist

As this example shows, PlistBuddy's syntax is clumsier and more verbose... but it's also far more powerful if you're trying to do something nontrivial.

  • While defaults can be given the full path to plist files that aren't in your ~/Library/Preferences folder, it always appends ".plist" to the filename, so if you're working with a file that doesn't have that extension, defaults is out.
  • PlistBuddy can easily drill down into arrays and dictionaries within the plist file; for example, to get the URL for the first permanent entry in the right side of your dock, you'd just refer to :persistent-others:0:tile-data:file-data:_CFURLString. (Note that arrays are 0-indexed, so :persistent-others:0 is the first element, :persistent-others:1 is the second, etc). Something like this:

    fileURL=$(/usr/libexec/PlistBuddy -c "print :persistent-others:0:tile-data:file-data:_CFURLString" ~/Library/Preferences/com.apple.dock.plist)
    

    ...and that's not really something defaults can do.

Upvotes: 5

Related Questions