I made a small automator app to help me launch and end apache ( another for mysql), so that I don't have to go to the terminal and do it ( yes I'm that lazy).

now here is the applescript I use for it:

on run {input, parameters}

set apache2state to (do shell script "/bin/ps -arx |/usr/bin/grep apache2 |wc -l")
repeat until apache2state does not start with " "
    set apache2state to text 2 thru -1 of apache2state
end repeat
if apache2state is equal to "3" then
    do shell script "/opt/local/bin/port load apache2" with administrator privileges
    do shell script "/opt/local/bin/port unload apache2" with administrator privileges
end if

end run

Now this works, except for the fact that I'm actually comparing to integer values that are relative to the number of processes that apache is running.. so it's not really reliable.

Is there a better way to test if apache (and mysql, I have another script just the same) is running. Problem is that when they are shut off the shell command will return an integer value just the same ( and not just a 1 for the grep process..)


EDITED to specify thatthe solution up here worked badly because the grep would return any instance of the apache threads and any other process that said apache ( like tail -r /var/log/apache2/error.log for instance).

Accepted Answer

The running state of a service can be tested with the following command:

/sbin/service --test-if-configured-on "org.apache.httpd"

This however might not work for services installed with MacPorts.

Also see the answer to the this question.

Since the command service is deprecated under Snow Leopard, you can alternatively use launchctl to obtain the running state of a service. The command can be invoked from AppleScript in the following way:

    do shell script "/bin/launchctl list | grep -q org.apache.httpd" with administrator privileges
    set apache2Running to true
on error
    set apache2Running to false
end try
Written by sakra
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki