Wednesday, March 7, 2012

Stupid Unix Tricks... Part 1

So, let's say you're trying to figure out if the database (or E-Business Suite) is down. Now, the logical way is use the Unix commands ps and grep to check for a particular process. Generally speaking, we would look for the SMON process for that particular instance.

However, maybe you're looking for something else that has multiple processes and you want to see that they're all shut down.

We're going to use a database as an example (largely because I assume you are familiar with the database). The basic command would be:

ps -ef|grep ora_smon_PROD
oracle 10445 6643 0 15:32 pts/0 00:00:00 grep ora_smon_PROD
oracle 19710 1 0 Feb28 ? 00:00:36 ora_smon_PROD

However, the problem here is that it also gives our grep command. To get around that, we can strip it out using grep -v grep (which would strip from our results anything that contains the string grep). Additionally, maybe we want to get something we can use in an if statement. The simplest way to do that is to count the number of lines returned by the command. That can be done by piping the output through the wc -l command. Our final command will look like this:

ps -ef|grep ora_smon_PROD|grep -v grep |wc -l

So, assuming that we just wanted to look for SMON we can build our if statement like this:

if [ `ps -ef |grep ora_smon_PROD|grep -v grep |wc -l` -gt 0 ]; then
   echo "SMON is UP"
else
   echo "SMON is DOWN"
fi

Now, let's assume that you want to check for PMON as instead:

if [ `ps -ef |grep ora_pmon_PROD|grep -v grep |wc -l` -gt 0 ]; then
   echo "PMON is UP"
else
   echo "PMON is DOWN"
fi

But what if you wanted to make sure that they were BOTH down?

if [ `ps -ef |grep -e ora_pmon_PROD -e ora_smon_PROD|grep -v grep |wc -l` -gt 0 ]; then
   echo "PMON and SMON are UP"
else
   echo "PMON and SMON are DOWN"
fi

The key here is grep -e. Because grep allows you to use the -e flag more than once per invocation, you can specify multiple strings to search for. Multiple -e strings are treated as a logical "or" by grep when it's parsing the input.

As with everything, your results may vary. Different platforms may have different versions of grep with different capabilities. This example was tested on Linux.

James

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.