I am trying to check whether specific rules in IPTables exists or not.#!/bin/bashif 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 existfiif 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 existfiI am checking below two rules:ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:8880ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:80Because 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.
Conditional Check for IPTables
bash;shell script;grep;iptables
The default action of grep is to print the matching line. To suppress that, you can use grep -q:#!/bin/bashif 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 existfiif 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 existfiYou could also simplify your script to this:#!/bin/bashrules=( 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 existdoneOr, if you want to have multiple actions, use an if/else like so:#!/bin/bashrules=( 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    fidone