What do ^$ and ^# mean?

I don't understand BADIPS=$(egrep -v "^#|^$" $tDB). Can you explain it? full code:

#!/bin/bash
# Purpose: Block all traffic from AFGHANISTAN (af) and CHINA (CN). Use ISO code. #
# See url for more info - http://www.cyberciti.biz/faq/?p=3402
# Author: nixCraft <www.cyberciti.biz> under GPL v.2.0+
# -------------------------------------------------------------------------------
ISO="af cn" 

### Set PATH ###
IPT=/sbin/iptables
WGET=/usr/bin/wget
EGREP=/bin/egrep

### No editing below ###
SPAMLIST="countrydrop"
ZONEROOT="/root/iptables"
DLROOT="http://www.ipdeny.com/ipblocks/data/countries"

cleanOldRules(){
$IPT -F
$IPT -X
$IPT -t nat -F
$IPT -t nat -X
$IPT -t mangle -F
$IPT -t mangle -X
$IPT -P INPUT ACCEPT
$IPT -P OUTPUT ACCEPT
$IPT -P FORWARD ACCEPT
}

# create a dir
[ ! -d $ZONEROOT ] && /bin/mkdir -p $ZONEROOT

# clean old rules
cleanOldRules

# create a new iptables list
$IPT -N $SPAMLIST

for c  in $ISO
do 
    # local zone file
    tDB=$ZONEROOT/$c.zone

    # get fresh zone file
    $WGET -O $tDB $DLROOT/$c.zone

    # country specific log message
    SPAMDROPMSG="$c Country Drop"

    # get 
    BADIPS=$(egrep -v "^#|^$" $tDB)
    for ipblock in $BADIPS
    do
       $IPT -A $SPAMLIST -s $ipblock -j LOG --log-prefix "$SPAMDROPMSG"
       $IPT -A $SPAMLIST -s $ipblock -j DROP
    done
done

# Drop everything 
$IPT -I INPUT -j $SPAMLIST
$IPT -I OUTPUT -j $SPAMLIST
$IPT -I FORWARD -j $SPAMLIST

# call your other iptable script
# /path/to/other/iptables.sh

exit 0

Solution 1:

^ is the a regular expression special character used to mark the start of the line, and $ marks the end of the line. They're used to anchor the expression at these points. So ^# is any line starting with #, and ^$ is an empty line (since there's nothing between the start and the end).

-v in grep negates the match, so this command is looking for lines that aren't commented out (not starting with #), or empty.

Solution 2:

egrep searches for files matching a pattern.

The -v (or --invert-match) option of egrep inverts the sense of matching, to select non-matching lines.

"^#|^$" evaluates to either a blank line or a line that starts with a # which is a comment line, neither of which are executed by bash. Inverting the match evaluates to lines that are not either blank lines or comment lines.

$tDB is a variable which stores the value of the local zone file.

Putting it all together the bad IPs (IPs to be blocked) are stored in BADIPS which stores the values of bad IPs obtained from a list of local zone files.