Mac OS X - Bash script if statement based on system status
You could use
[[ $(spctl --status) == "assessments enabled" ]] \
&& (echo "Gatekeeper is enabled."; do-additional-stuff) \
|| (echo "Gatekeeper is disabled."; do-other-stuff)
which is technically a one-liner. But it's hard to read if you are not used to such things; and it gets even harder as soon as there are a lot of additional commands. Depending on your coding style etc something like
gk_is_enabled() {
echo "Gatekeeper is enabled."
# do lots of additional stuff
}
gk_is_disabled() {
echo "Gatekeeper is disabled."
# do lots of other stuff
}
[[ $(spctl --status) == "assessments enabled" ]] && gk_is_enabled || gk_is_disabled
might work then.
In addition you can shorten the [[ $(spctl --status) == "assessments enabled" ]]
part (in any solution) to [[ $(spctl --status) == *enabled ]]
.
Also, if you want to go really crazy with showing off some bash skills you could do
assessments_enabled() {
echo "Gatekeeper is enabled."
# do lots of additional stuff
}
assessments_disabled() {
echo "Gatekeeper is disabled."
# do lots of other stuff
}
eval $(spctl --status | sed 's/ /_/')
Your example is clear, concise and maintainable but lacks any error checking. This example uses a case statement to parse the status and will exit if neither string is in the variable ->
status=$(spctl --status)
case $status in
'assessments enabled') echo "Gatekeeper is enabled."
#do more stuff
#and more stuff
;;
'assessments disabled') echo "Gatekeeper is disabled."
#do more stuff
#and more stuff
;;
*) echo "An error has occurred- Exiting script"
exit
;;
esac
It could also be written like this ->
if [[ $status == "assessments enabled" ]]
then
echo "Gatekeeper is enabled."
#do more stuff
elif [[ $status == "assessments disabled" ]]
then
echo "Gatekeeper is disabled"
#do more stuff
else
echo "An error has occurred- Exiting script"
exit
fi