Use iptables(8)to list the chain by redirecting stdout / stderr to /dev/null, and check the exit code. If the chain exists, it iptableswill come out of the truth.
This shell function from my iptables script interface:
chain_exists()
{
[ $# -lt 1 -o $# -gt 2 ] && {
echo "Usage: chain_exists <chain_name> [table]" >&2
return 1
}
local chain_name="$1" ; shift
[ $# -eq 1 ] && local table="--table $1"
iptables $table -n --list "$chain_name" >/dev/null 2>&1
}
Please note that I am using the parameter -n, so iptables is not trying to resolve IP addresses for host names. Without this, you will find that this feature will be slow.
:
chain_exists foo || create_chain foo ...
create_chain - . iptables, , .