1

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
1

3 Answers 3

4

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
0
3

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.

2

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

2
  • Backticks work, but it's worth mentioning that $() is considered best practice in modern versions of bash for legibility and nesting purposes. Jul 25, 2012 at 18:33
  • Indeed, and $() has more variable-alike format
    – sebelk
    Jul 26, 2012 at 11:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .