Search code examples
bashshelliptables

best way to check if a iptables userchain exist


I am trying to programmatically create user chains and delete them in iptables. I was wondering what is the best way to check if a user chain exist and if it does not create it.


Solution

  • Use iptables(8) to list the chain, redirecting stdout/stderr to /dev/null, and check the exit code. If the chain exists, iptables will exit true.

    This shell function is from my iptables front-end script:

    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
    }
    

    Note that I use the -n option so that iptables does not try to resolve IP addresses to hostnames. Without this, you'll find this function would be slow.

    You can then use this function to conditionally create a chain:

    chain_exists foo || create_chain foo ...
    

    where create_chain is another function to create the chain. You could call iptables directly, but the above naming makes it quite obvious what is going on.