因为在网上看到这篇文章:脚本分享 之 天朝全静态路由 « Hey! Linux,比较感兴趣其中的shell脚本,所以看了看源码,觉得其中的用awk计算子网掩码的方法特别好,在此记录一下(下面截取的是我比较感兴趣的代码片段):
#!/bin/bash basedir=$(dirname $0) wget http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest conf="${basedir}/delegated-apnic-latest" function check_conf(){ if [ ! -f ${conf} ]; then echo "No such file: ${conf}" echo "Please download it from http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest" exit 1 fi } function add_routes(){ oldgw=$(netstat -nr | grep '^default' | grep -v 'ppp' | sed 's/default *([0-9.]*) .*/1/' | grep -Ev '^$') #dscacheutil -flushcache all_subs=$(grep CN ${conf} | grep ipv4 | awk -F '|' '{print $4"/"$5}') echo -n "Adding the routes..." for subnet in ${all_subs} do subneti=$(echo ${subnet} | cut -d/ -f1) rawnetm=$(echo ${subnet} | cut -d/ -f2) subnetm=$(awk -v c=${rawnetm} 'function log2(x){if(x<2)return(pow);pow--;return(log2(x/2))}BEGIN{pow=32;print log2(c)}') route add ${subneti}/${subnetm} "${oldgw}" > /dev/null done echo " Done" }
其中:
all_subs=$(grep CN delegated-apnic-latest | grep ipv4 | awk -F ‘|’ ‘{print $4″/”$5}’)
for subnet in ${all_subs}
do
subneti=$(echo ${subnet} | cut -d/ -f1)
rawnetm=$(echo ${subnet} | cut -d/ -f2)
subnetm=$(awk -v c=${rawnetm} ‘function log2(x){if(x<2)return(pow);pow–;return(log2(x/2))}BEGIN{pow=32;print log2(c)}‘)
done
echo ” Done”
因为delegated-apnic-latest这个文件中的第5列为划分给的IP地址块,第6列为地址块中的个数,由此计算对应的子网掩码,这里用的awk方法对于我来说感觉非常惊艳!
还有就是dirname命令的学习(示例说明了一切):
NAME
dirname – strip last component from file name
SYNOPSIS
dirname NAME
dirname OPTION
DESCRIPTION
Output NAME with its last non-slash component and trailing slashes removed; if NAME contains no /’s, output `.’ (meaning the current directory).
–help display this help and exit
–version
output version information and exit
EXAMPLES
dirname /usr/bin/
Output “/usr”
dirname stdio.h
Output “.”
SEE ALSO
basename(1), readlink(1)
GNU coreutils 8.12.197-032bb September 2011 DIRNAME(1)