mvelez83
mvelez83

Reputation: 161

if else statement incorrect output

I'm working on a custom Nagios script that will monitor cPanel to make sure it is running and give back a status depending on what it gets from an output of service cpanel status. This is what I have:

##############################################################################
#   Constants

cpanelstate="running..."

ALERT_OK="OK - cPanel is running"
ALERT_CRITICAL="CRITICAL - cPanel is NOT running"
###############################################################################

cpanel=$(service cpanel status | head -1)

if [ "$cpanel" = "$cpanelstate" ]; then

        echo $ALERT_OK
        exit 0
else
        echo $ALERT_CRITICAL
        exit 2

fi

exit $exitstatus

When I run the script, this is the output I get:

root@shared01 [/home/mvelez]# /usr/local/nagios/libexec/check_cpanel 
CRITICAL - cPanel is NOT running

When I run the script, cPanel IS RUNNING but this is the output I get. As a matter of fact, no matter what the status reports for cPanel this is the output that comes out. When I comment out the ELSE, ECHO and EXIT 2 statement:

#else
#       echo $ALERT_CRITICAL
#       exit 2

It gives back a blank output:

root@shared01 [/home/mvelez]# /usr/local/nagios/libexec/check_cpanel 
root@shared01 [/home/mvelez]#

I'm not sure what I'm not doing correctly as I am very new to bash scripting and trying to learn as I go along. Thank you in advanced for any and all help very very much!

Upvotes: 0

Views: 413

Answers (2)

mklement0
mklement0

Reputation: 439257

@Oleg Gryb's answer solves your problem, but as for why your original script didn't work:

[ "$cpanel" = "$cpanelstate" ] compared the full command output - e.g., cpsrvd (pid 10066) is running..., against a substring of the expected output, running... for equality, which will obviously fail.

The solution is to use bash's pattern matching, provided via the right-hand side of its [[ ... ]] conditional (bash's superior alternative to the [ ... ] conditional):

[[ "$cpanel" == *"$cpanelstate" ]]

* represents any sequence of characters, so that this conditional returns true, if $cpanel ends with $cpanelstate (note how * must be unquoted to be recognized as a special pattern char.)

Upvotes: 0

Oleg Gryb
Oleg Gryb

Reputation: 5249

The code below should work, but you might need to run it with sudo, because 'service' might not be available for ordinary users.

#!/bin/bash

##############################################################################
#   Constants

cpanelstate="running"

ALERT_OK="OK - cPanel is running"
ALERT_CRITICAL="CRITICAL - cPanel is NOT running"
###############################################################################

cpanel=$(service apache2 status | head -1)
echo CPANEL $cpanel
if [[ $cpanel == *$cpanelstate* ]]; then

        echo $ALERT_OK
        exit 0
else
        echo $ALERT_CRITICAL
        exit 2

fi

Upvotes: 1

Related Questions