Brew Extension Attribute

ammonsc
Contributor II

Trying to get an EA to report if homebrew is installed so I can scope a GIT update.

#!/bin/bash

## Work Area ####################

which brew

if [ $? = /usr/local/bin/brew ]

then
    echo "<result>brew installed</result>"
else
    echo "<result>brew not installed</result>"
fi

I only get "brew not installed"

any ideas?

3 REPLIES 3

m_donovan
Contributor III

Try this:

#!/bin/bash

if [ ! -z $(which brew) ];then
  echo "<result>Brew installed</result>"
else
  echo "<result>Brew Not installed</result>"
fi

exit 0

alexjdale
Valued Contributor III

$? returns the error code for the last command, not the result printed to stdin. It will never return the file path.

brockwalters
Contributor II

@ammonsc your test command does not work because the output of "$?" is always an exit code (i.e., an integer...)

It is correct that "$?" captures the last command's exit code in the current shell. You may not get the result you intend when using "$?" in a Jamf extension attribute script because EA scripts always run as the root user & because commands may be running in a subshell. Shellcheck also advises against using "$?" in test commands this way.

@m_donovan using the which built-in (zsh) or the /usr/bin/which binary (which still exists but is no longer the macOS default...) for something like this is a good idea, however, the above could never work because the which commands reads the current user's $PATH variable...

When Jamf runs an EA script that includes the which command it will only be able to read the root user's $PATH  unless you do the following:

 

root# crntusr="$(/usr/bin/stat -f %Su /dev/console)"
root# /usr/bin/sudo -i -u "$crntusr" /usr/bin/which brew
/opt/homebrew/bin/brew

 

From man sudo:

 

-i, --login Run the shell specified by the target user's password database entry as a login shell.  This means that login-specific resource files such as .profile, .bash_profile or .login will be read by the shell.

...

-u user, --user=user
Run the command as a user other than the default target user (usually root).  

 

Running the command as the logged in user in this case is not enough. You also need to read the logged in user's shell environment which includes their $PATH variable.