The OS X /usr/libexec/PlistBuddy is a well-executed CLI:
- if successful, its exit code is
0 - in case of failure, its exit code is not equal to zero
- its regular output is sent to
stdout , error messages are sent to stderr
There are various ways to verify success; eg:.
# Query and save the value; suppress any error message, if key not found. val=$(/usr/libexec/PlistBuddy -c 'print ":SomeKey"' file 2>/dev/null) # Save the exit code, which indicates success v. failure exitCode=$? if (( exitCode == 0 )) then # OK # handle success .... else # handle failure ... fi
Update 1
Here is a snippet of your specific use case; you can run it as is to see how it works (it uses the Plist file in which the Finder saves its settings):
# Loop over keys and retrieve the corresponding values. # If the key doesn't exist, assign '0'. for key in ':AppleShowAllFiles' ':NoSuchKey'; do val=$(/usr/libexec/PlistBuddy -c "print \"$key\"" \ ~/Library/Preferences/com.apple.finder.plist 2>/dev/null || printf '0') echo "Value retrieved: [$val]" done
As you will see, $val will contain 0 in the case of a 2nd, nonexistent key.
2>/dev/null suppress stderr output (error messages) and operator || used to provide an alternative command to create output in the event that a call to PlistBuddy indicates a failure (via its exit code).
The only caveat is that you cannot distinguish a nonexistent key from a more fundamental failure, such as a nonexistent or damaged Plist file. Processing will be more attractive since PlistBuddy does not use different exit codes to distinguish between these cases.
Update 2
Here's a simplified version of your code that includes the desired default 0 logic:
# Collect temperatures. Data_results=() for i in {0..3} do Data_results+=( $(/usr/libexec/PlistBuddy \ -c "print :process:$i:testname:result" "$fileName" 2>/dev/null || printf '0') ) done # Calculate average AverageValue=$(bc <<< \ "scale=10; $(( ${Data_results[@]/%/ +} 0 )) / ${#Data_results[@]}") echo "average for test name: " $AverageValue
Note: $(( ... )) is an arithmetic extension (only integers) that uses a little trick to sum the elements of the array: ${Data_results[@]/%/ +} + to each element of the array. For example, the input array from (1 2 3) will expand to 1 + 2 + 3 + ; since this leaves a dangling + , I just added another 0 to form the correct expression. In combination with dividing by ${#Data_results[@]} - the number of elements in the array - the command then works with an array of any size.
mklement0
source share