Using Plistbuddy to delete a string from an array

I have two previous posts about using Plistbuddy to add to an array in a .plist file (specifically Munki's SelfServeManifest file):
Bash script to add optional installs for Munki
Terminal command to mark a Munki optional install for installation

What if you want to remove an item from the array? It's not a simple thing to do. One option you have is to read the entire array, remove the offending entry, and then write back the modified array.

The most straightforward (but still roundabout) way I could think to do it is to find the index of the offending entry and then remove the entry by index number. Here's an example:

# See if Acrobat DC is set to be installed in the self-serve manifest
acrobatDC=$(/usr/libexec/Plistbuddy -c "Print managed_installs" /Library/Managed\ Installs/manifests/SelfServeManifest | grep -n "AdobeAcrobatDC" | awk -F ":" '{print $1}')

if [ ! -z "$acrobatDC" ]; then
# Item to delete is the number minus two

sudo /usr/libexec/Plistbuddy -c "Delete :managed_installs:$itemToDelete" /Library/Managed\ Installs/manifests/SelfServeManifest

The first command puts into a variable the output of reading the managed_installs after finding out what line number the offending entry is on. Since it prints the word "Array {" on the first line and since the indexing starts at zero, the third line would be index 1, the fourth line would be index 2, etc.

So, assuming the variable is not empty, the item to delete is the line number minus 2, and then we can remove it by that index number.

Leave a Reply

Your email address will not be published. Required fields are marked *