How to Use Grep in Linux for Multiple '&' Based Search

I am trying to find out of two process are running in linux where my oracle is installed pmon and smon i used below command for it

ps -ae | grep pmon > /dev/null;echo $?

and

 ps -ae | grep smon > /dev/null;echo $?

now i want to optimize both commands in to single i know there is option in grep as below

ps -ae | grep 'pmon\|smon' > /dev/null;echo $?

but problem here is if any of process running it returns 0 error code but i want an AND based search instead. Command should return 0 only if both process running.

3 Answers

I would suggest you used something like this:

if ps -ae | grep -q pmon && ps -ae | grep -q smon; then
    echo "pmon and smon are running"
fi

The -q switch to grep prevents any output so you don't have to redirect to /dev/null yourself. If you have pgrep, you may be able to use that instead of piping ps to grep.

Of course, you could "optimise" this onto one line, optionally using another && instead of an if but I really don't see the advantage!

You can try this:

pgrep pmon > /dev/null && pgrep smon > /dev/null; echo $?

or

pgrep pmon > /dev/null && pgrep smon > /dev/null && echo both running

Try this :

ps -ae | egrep 'pmon,smon'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest