How can I add an Array to a Plist using PlistBuddy? How can I add an Array to a Plist using PlistBuddy? shell shell

How can I add an Array to a Plist using PlistBuddy?


There may be a better way to do this, but I have solved this problem by counting the elements in the source array and then copying them over individually.

${PLISTBUDDY} -c "Add PreferenceSpecifiers:$DEST_INDEX:Titles array" ${DEST_PLIST}    ${PLISTBUDDY} -c "Add PreferenceSpecifiers:$DEST_INDEX:Titles:0 string 'TITLE_1'" ${DEST_PLIST} ${PLISTBUDDY} -c "Add PreferenceSpecifiers:$DEST_INDEX:Titles:1 string 'TITLE_2'" ${DEST_PLIST} etc... 


It may fix your problem but it is not the right way to implement in larger merging scripts. Check my ans below.

/usr/libexec/PlistBuddy -x -c "Print PreferenceSpecifiers" ${FROM_PLIST} > ${TO_PLIST}


For something simple like an array of strings, here is code that will combine an arbitrary number of arrays. This example uses the UIAppFonts array common in iOS Info plists.

TMP_NAME=`basename $0`TMP_DIR=`mktemp -d ${PROJECT_TEMP_DIR}/${TMP_NAME}.XXXXXX` || exit 1FONTS_PLIST="${TMP_DIR}/Fonts.plist"/usr/libexec/PlistBuddy -c "Add UIAppFonts array" "${FONTS_PLIST}"# Iterate through each array, adding to the array entry in the temporary plistindex=0for arg; do  status=0  inner_index=0  while [ ${status} -eq 0 ]; do    set +e    # No easy way to get array length, so keep going until we go out of bounds    entry=`/usr/libexec/PlistBuddy -c "Print UIAppFonts:${inner_index}" "${arg}" 2> /dev/null`    status=${?}    set -e    if [ ${status} -eq 0 ]; then      /usr/libexec/PlistBuddy -c "Add UIAppFonts:${index} string ${entry}" "${FONTS_PLIST}"      index=`expr ${index} + 1`      inner_index=`expr ${inner_index} + 1`    fi  donedone