Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add values to nested arrays or dicts using the "defaults write" command?

Tags:

macos

defaults

Consider a preference plist with a dict that contains an array:

Let's create it:

defaults write org.my.test '{aDict = {anArray = ();};}'

Then read it back to see the structure better:

$defaults read org.my.test
{
    aDict = {
        anArray = (
        );
    };
}

Now, how do I add a value to anArray using the defaults write command?

I know that there is the -array-add type for adding values to an array, but how do I specify the key path to the array element?

I've tried this, but that doesn't work:

defaults write org.my.test aDict.anArray -array-add "a value"

In fact, I need to add a non-string type, so I also need to be able to specify the type, e.g. -bool YES.

(Note: I cannot use PlistBuddy nor plutil as this needs to affect live preferences)

like image 724
Thomas Tempelmann Avatar asked Apr 23 '14 19:04

Thomas Tempelmann


1 Answers

Use plutil and your life will be better. Defaults doesn't support key paths.

> defaults write org.my.test '{aDict = {anArray = ();};}'

> defaults read org.my.test
{
    aDict =     {
        anArray =         (
        );
    };
}

> plutil -insert aDict.anArray.0 -bool YES ~/Library/Preferences/org.my.test.plist

> defaults read org.my.test
{
    aDict =     {
        anArray =         (
            1
        );
    };
}

I used defaults read just to prove that the expected inputs are the same, but you'll probably use plutil -p ~/Library/Preferences/org.my.test.plist to read the file instead if you start using plutil more.

like image 122
Liyan Chang Avatar answered Oct 17 '22 23:10

Liyan Chang