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?


SERV='/sbin/service iptables status'
EXPR='Firewall is stopped.'
        if [ "$SERV" = "$EXPR" ]
                        echo 'Firewall is not Running'
                        exit 2
                        echo 'OK'
                        exit 0

3 Answers 3


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."
    echo "Houston, we have a problem."

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.


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)"


SERV=`/sbin/service iptables status`


  • 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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