Conditional Check for IPTables

I am trying to check whether specific rules in IPTables exists or not.

#!/bin/bash

if iptables -L -n | grep -- "ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:8880";
 then
     echo "ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:8880 exists"
 else
     echo "ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:8880 does not exist"
fi

if iptables -L -n | grep -- "ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:80";
 then
     echo "ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:80 exists"
 else
     echo "ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:80 does not exist"
fi

I am checking below two rules:

ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:8880

ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:80

Because those two rules already exists and conditions run the TRUE case, terminal also outputs the result of the grep in conditional check unnecessarily. grep somehow does not output for FALSE case.

How can I prevent the grep to output for TRUE case?

And how can I combine those separate two if conditionals into a single OR conditional?

BTW, my IPTables is old version and can not use -C argument.

Answer

The default action of grep is to print the matching line. To suppress that, you can use grep -q:

#!/bin/bash

if iptables -L -n | grep -q -- "ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:8880";
 then
     echo "ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:8880 exists"
 else
     echo "ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:8880 does not exist"
fi

if iptables -L -n | grep -q -- "ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:80";
 then
     echo "ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:80 exists"
 else
     echo "ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:80 does not exist"
fi

You could also simplify your script to this:

#!/bin/bash

rules=( "ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:8880"  "ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:80")


for rule in "${rules[@]}"
do
    iptables -L -n | grep -q "$rule" && echo "$rule exists" || echo "$rule does not exist"
done

Or, if you want to have multiple actions, use an if/else like so:

#!/bin/bash

rules=( "ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:8880"  "ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:80")


for rule in "${rules[@]}"
do
    if iptables -L -n | grep -q "$rule"
    then
        echo "$rule exists"
    else
        echo "$rule does not exist"
    fi
done

Leave a Reply

Your email address will not be published. Required fields are marked *