Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I have the following simple script to check if iptables is running or not. Why does it always returns 'OK' no matter what the status is?

#!/bin/bash

#IPT='iptables'
SERV='/sbin/service iptables status'
EXPR='Firewall is stopped.'
        if [ "$SERV" = "$EXPR" ]
                 then
                        echo 'Firewall is not Running'
                        exit 2
                else
                        echo 'OK'
                        exit 0
        fi
share|improve this question
    
eflo.net/VICIDIALforum/viewtopic.php?p=71701 perhaps of interest? –  Jason Smith Jul 25 '12 at 15:25
add comment

3 Answers

up vote 1 down vote accepted

The init script for iptables will never return exactly that string; it will always have something else in it, and there are also failure conditions which don't match that string at all.

Instead, you should check the exit code from the script, as it (on EL and Fedora) returns non-zero if the firewall is not active and zero if it is active.

/sbin/service iptables status >/dev/null 2>&1
if [ $? = 0 ]; then
    echo "All systems go."
else
    echo "Houston, we have a problem."
fi
share|improve this answer
    
Awesome, thanks! –  j5iApart2 Aug 1 '12 at 15:55
add comment

You are setting $SERV to equal the literal string value "/sbin/service iptables status", you need it to execute the command and store the result. You can verify this by echoing $SERV. As written, it will always evaluate to not-equal.

SERV=$(/sbin/service iptables status)

Also, make sure the output is as expected. My version returns iptables: Firewall is not running. (Yours of course may vary.)

Read more about subshells at the Advanced Bash-Scripting Guide.

share|improve this answer
add comment

The scripts is doing what it says. Bear in mind that [ "$SERV" = "$EXPR" ] is comparing strings , and they are non-equal.

So, exit status of test will be always non-zero, so will go always to "else".

What you need is to use Command Subtitution, instead of SERV='/sbin/service iptables status' you should use either

SERV="$(/sbin/service iptables status)"

or

SERV=`/sbin/service iptables status`

HTH

share|improve this answer
    
Backticks work, but it's worth mentioning that $() is considered best practice in modern versions of bash for legibility and nesting purposes. –  Aaron Copley Jul 25 '12 at 18:33
    
Indeed, and $() has more variable-alike format –  sebelk Jul 26 '12 at 11:54
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.