- 论坛徽章:
- 0
|
最近一直在学习shell, 但是写脚本的机会并不是很多,但是学习shell的最好的方式就是多写脚本,多用不同的方式去解决同一个问题。
为了提高自己的shell水平,尝试把每一个的重复性工作,都用shell来完成,作为自己使用的小工具(毕竟别人不一定会觉得用的爽 )
这是我的文章链接:http://diaocow.iteye.com/blog/1674074- #!/bin/bash
- ##############################
- # 切换hosts的工具类 swich hosts
- #
- # --------hosts 文件格式--------
- # ==offline
- # ip list...
- # ==offline
- #
- # ==online
- # ip list...
- # ==online
- # --------hosts 文件格式--------
- #
- # 操作:sh shosts.sh offline 开启offline这组host绑定
- #
- # kang.zhouk 2012-9-8
- #
- ##############################
- # 检测用户是否输入了group tag
- if [[ -z $1 ]] ; then
- echo "Error: Please input a group tag! eg. offline"
- fi
- HOSTS="testdata" # hosts文件(这里,你需要替换成/etc/hosts)
- HOSTS_TEMP="host.tmp" # hosts临时文件
- GROUP_TAG="==$1" # 需要打开的组
- # 检测group tag有效性
- if ! grep -q "$GROUP_TAG" "$HOSTS" ; then
- echo "Error: there is no group tag named $GROUP_TAG in $HOSTS"
- exit -111
- fi
- # 函数:判断字符串是否为IP
- isIp() {
- echo $1 | grep -E -q '([0-9]+\.){3}[0-9]'
- ip_result=`echo $?`
- }
- # clean临时文件
- : > $HOSTS_TEMP
- # group tag 计数
- start_flag=0
- # 处理hosts
- cat $HOSTS | while read line ; do
- if echo $line | grep -q $GROUP_TAG; then
- start_flag=$((start_flag + 1))
- fi
- isIp "$line"
- if [[ $start_flag == 1 && $ip_result == 0 ]] ; then
- # 去掉开头的注释符
- line=${line/#\#/}
- elif [[ $ip_result == 0 ]] ; then
- # 在行开头添加注释符
- if ! echo $line | grep -q '^ *#' ; then
- line=\#$line
- fi
- fi
- echo "$line" >> $HOSTS_TEMP
- done
- # 重新生成hosts
- cat $HOSTS_TEMP > $HOSTS
- rm -rf $HOSTS_TEMP
复制代码 现在我们来测试下这个脚本:
我们准备下测试数据(脚本中的HOSTS变量指定hosts文件,目前我们暂定义为testdata):
[diaocow@ubuntu]$ cat testdata
==offline
72.51.30.13 offline.test1.com
72.20.123.321 offline.test2.com
==offline
==online
12.56.92.97 online.test1.com
12.56.38.84 online.test2.com
==online
将host切换到线上环境
[diaocow@ubuntu]$ sh shosts.sh online
[diaocow@ubuntu]$ cat testdata
==offline
#72.51.30.13 offline.test1.com
#72.20.123.321 offline.test2.com
==offline
==online
12.56.92.97 online.test1.com
12.56.38.84 online.test2.com
==online
重复执行 sh shosts.sh online 不会有任何问题
我们在尝试切换成线下环境
[diaocow@ubuntu]$ sh shosts.sh offline
[diaocow@ubuntu]$ cat testdata
==offline
72.51.30.13 offline.test1.com
72.20.123.321 offline.test2.com
==offline
==online
#12.56.92.97 online.test1.com
#12.56.38.84 online.test2.com
==online
一切OK
在脚本的编写过程中,我经常使用这两个命令
sh -n shosts.sh online # 检测脚本语法错误
sh -x shosts.sh online # 详细打出脚本每一步执行过程
|
|