Search code examples
macosbashterminalmdmprofiles

Install Check Script that checks Profiles -P for a specific profile


I am trying to write up a instal check script that runs profiles -Pand exits based on the response.

We use a profile from meraki which the output looks like so (if installed):

_computerlevel[1] attribute: profileIdentifier: com.meraki.sm.mdm
There are 1 configuration profiles installed

Is there a way to check this out put for this exact response?

I was thinking something like:

#!/bin/bash
output=profiles -P
if [ output = com.meraki.sm.mdm ]; then
exit 0;
else
exit 1;

Any ideas?


Solution

  • Try the following:

    #!/bin/bash
    
    if sudo profiles -P | egrep -q ': com.meraki.sm.mdm$'; then
      exit 0
    else
      exit 1
    fi
    
    • Output from sudo profiles -P (note that profiles always requires root privileges) is sent via a pipe (|) to egrep; the two commands form a pipeline.
    • egrep -q ': com.meraki.sm.mdm$' searches through profile's output:
      • -q (quiet) option produces no output and simply signals via its exit code whether a match was found (0) or not (1).
      • ': com.meraki.sm.mdm$' is a regular expression that matches string 'com.meraki.sm.mdm' found at the end of the line ($), preceded by ': '.
      • (egrepis the same asgrep -E` - it activates support for extended regular expressions - not strictly necessary here, but generally advisable for fewer surprises).
    • The if statement evaluates to true if the pipeline returns exit code 0, and to false otherwise (nonzero). Note that by default it is the last command in the pipeline whose exit code determines the pipeline's overall exit code.

    Incidentally, if all you wanted to do is to have your script reflect whether the string was found or not (i.e., if you don't need to take further action inside your script), the following would suffice:

    sudo profiles -P | egrep -q ': com.meraki.sm.mdm$'
    exit $?   # Special variable `$?` contains the most recent command's exit code
    

    If you wanted to exit your script right after in the event of failure only:

    sudo profiles -P | egrep -q ': com.meraki.sm.mdm$' || exit
    
    # Alternative, with error message:
    sudo profiles -P | egrep -q ': com.meraki.sm.mdm$' ||
      { ec=$?; echo 'Profile not installed.' >&2; exit $ec; }
    

    Conversely, if you wanted to exit right after in the event of success:

    sudo profiles -P | egrep -q ': com.meraki.sm.mdm$' && exit