Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I know I have to count how many instances are running:

ps x | grep apache2 | wc -l 

result if it's running: 2, or else: 1

I also know there is a command called test that I could use to perform the verification, but I don't know how to use test with wc

share|improve this question
W​h​ich distro? – Ignacio Vazquez-Abrams Apr 16 '10 at 13:56
"/sbin/service apache2 status" will show if the service is start or stop. – Chau Chee Yang Apr 16 '10 at 14:02
@Ignacio ubuntu – Jader Dias Apr 18 '10 at 14:11
up vote 5 down vote accepted

The startup scripts on most Linux distributions handle this, by saving the Process ID of the service (daemon) when they launch it.

These PIDs are typically stored in /var/run/. For example on my system Apache2 stores it original or parent process ID (useful for pre-forked processes) in /var/run/ So you can then send signals such as SIGHUP or SIGSTOP to the process to signal either a configuration reload or to stop the service (daemon).

One note to help with your ps ax style process searching is to use a little trick to escape the grep's regular expression pattern used for matching, such that it doesn't match itself. E.g. ps ax | grep [a]pache2 | wc -l

man test gives you the basics of the test command. For simple tasks in shell scripting, it best to avoid being dependent on which shell you are using. Normally for basic scripting, writing scripts targeting the Borne Shell (/bin/sh) is recommended, as this tends to be the most popular lowest common denominator.


RC= `ps ax | grep [a]pache2 | wc -l`

if [ $RC -gt 0 ]; then
  kill -SIGSTOP `cat /var/run/`
share|improve this answer
What a clever idea to use grep [a]pache2! Thanks for that. – Jul 21 '13 at 13:05

If you are working with bash, you can do it with conditional checks:

if [ $num -eq "1" ]; then
        echo "got 1"

if [ $num -eq "2" ]; then
        echo "got 2"
share|improve this answer
how to make num equal to ps x | grep apache2 | wc -l ? – Jader Dias Apr 16 '10 at 13:45
@Jader, I've included an example in my answer. – mctylr Apr 16 '10 at 14:22
if (( $(ps x | grep [a]pache2 | wc -l) > 0 ))


case $(ps x | grep [a]pache2 | wc -l) in

The square brackets used in that way in the grep command suppresses the grep itself from being included in its own output. This will make the process count 0 if apache isn't running.

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .