Friday, January 8, 2010

Checking Simple Conditions

You want to check for a condition such as whether a critical database background process is running and send an e-mail if there is a problem.

Solution

Use the if/then/else Bash control structure to check for a condition and perform an appropriate action. The following example uses an if/then/else structure to determine whether the Oracle system monitor process is running and sends an e-mail if the process is not detected:

#!/bin/bash
SID=SAND
critProc=ora_smon
ps -ef grep -v 'grep' grep ${critProc}_$SID
if [ $? -eq 0 ]; then
echo "$SID is available."
else
echo "$SID has issues." mail -s "problem with $SID" bbill@gmail.com
fi
exit 0

The previous example uses the $? variable. This variable is often used after conditional statements to evaluate the success or failure of the previous command. The $? contains the status of the last executed command. If the previously executed command was successful, then the $? variable will contain a zero; otherwise, it will contain a nonzero value.

How It Works

The if/then/else control structure comes in three basic forms. The first one states that if a condition is true, then execute the following commands. Its syntax is as follows:

if condition ; then
commands
fi

On the first line of code in the previous example, the keyword then is a separate command, so you must insert a semicolon to indicate the end line termination point of the if keyword. Another way of executing the previous bit of code would be as follows:

if condition
then
commands
fi

The next form of the if/then/else structure states if a condition is true, execute the following commands. If the first condition is false, then execute a separate set of commands. Its syntax is as follows:

if condition ; then
commands
else
commands
fi

The third form of the if/then/else structure states that if a condition is true, then execute the first set of commands; otherwise, check for the next condition, and if it is true, execute the commands. This functionality is enabled with the elif keyword. You can have many elif conditions in this form. Its syntax is as follows:

if condition ; then
commands
elif condition
commands
elif condition
commands
fi

No comments:

Post a Comment