Shell脚本是我们运维人员管理的最基础知识,下面就是我在学习过程中的一些小例子(比起大牛来说)。写这篇博客的目的,是为了记录自己学习脚本的历程,也是为了能和读者一起探讨学习。# Example1: 自动创建脚本的模板 脚本名:creat_scripts.sh
# 功能描述:creat_scripts.sh SCRIPTS_NAME 如果创建的脚本名文件不存在,则创建成脚本文件;
# 如果对应的文件存在,且为脚本文件,则打开文件到最后一行;
# 如果对应的文件存在,但不是脚本文件,则提示退出。
#!/bin/bash
# Description: create a script model
# Version: 0.0.1
# Author: Alex
# Date: 2014-07-09
# 判断参数问题
if [ $# -lt 1 ];then
echo "Usage: `basename $0` SCRPIPT_NAME."
exit 2
fi
if [ ! -e "$1" ];then
/bin/touch "$1"
cat > "$1" <
#!/bin/bash
# description:
# version:
# date:
# author: Alex
# license: GPL
EOF
vim + "$1"
# 这里判断脚本是否正常退出的办法是,判断是否存在 .SCRIPTS_NAME.swp隐藏文件
if [ ! -e "`/usr/bin/dirname $1`.$1.swp" ];then
[ ! -x $1 ] && /bin/chmod +x "$1"
bash -n $1 &>/dev/null
result=$?
[ $result -ne 0 ] && echo "$(bash -n $1)"
fi
else
[[ `/usr/bin/file "$1"` =~ Bourne-Again\ shell\ script\ text\ executable$ ]] \
&& vim + "$1" || echo "This is not scripts." && exit 2
if [ ! -e "`/usr/bin/dirname $1`.$1.swp" ];then
[ ! -x $1 ] && /bin/chmod +x "$1"
bash -n $1 &>/dev/null
result=$?
[ $result -ne 0 ] && echo "$(bash -n $1)"
fi
fi# Example2:判读一个IP v4地址是否为A,B,C类地址,如果是则打印出默认掩码
# 此脚本是通过Example1的脚本创建出来的
#!/bin/bash
# description:
# version:0.0.0
# date:2014-07-16
# author: Alex
# license: GPL
# 下面是IP地址十进制表示是,四位的正则表达式
fistip="[1-9]|[1-9][0-9]|11[0-9]|12[1-68-9]|1[3-9][0-9]|2[0-1][0-9]|22[0-3]"
secondip="[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]"
thirdip="[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]"
fourip="[1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4]"
read -p "Please input ip addr:" ip_addr
while true ;do # 等价于 while : ;do
if echo "$ip_addr" | grep -E "^\\.\\.\\.\$" &>/dev/null;then
# 下面的这一句和上面应该有相同功能,但实际上不是,笔者正在研究
#if [[ "$ip_addr" =~ ^\\.\\.\\.\$ ]];then
ifconfig eth0 $ip_addr &>/dev/null
head_ip=`echo "$ip_addr" | cut -d. -f1`
if [ $head_ip -ge 1 -a $head_ip -le 126 ];then
echo "$ip_addr mask is 255.0.0.0"
elif [ $head_ip -ge 128 -a $head_ip -le 191 ];then
echo "$ip_addr mask is 255.255.0.0"
elif [ $head_ip -ge 192 -a $head_ip -le 223 ];then
echo "$ip_addr mask is 255.255.255.0"
fi
exit 3
else
read -p "Please again input ip addr:" ip_addr
fi
done
以后会不定期更新.....