Linux学习笔记十六:shell函数练习
作者:互联网
可以组织一些常用的方法,写到函数里面,作为公共的方法方便shell脚本调用,这样可以简化步骤,提高可读性,不用重复造轮子了。
# 调用系统公共函数方法
. /etc/init.d/functions
阶乘
fact(){
if [ $1 -eq 1 ];then
echo 1
else
echo $[$1*$(fact $[$1-1])]
fi
}
汉诺塔
#local i=1
hanio(){
if [ $1 -eq 1 ];then
echo "第$i步:$2-->$4"
else
hanio $[$1-1] $2 $4 $3
let i+=1
echo "第$i步:$2-->$4"
let i+=1
hanio $[$1-1] $3 $2 $4
fi
}
判断系统版本
sys_ver(){
VER=`cat /etc/redhat-release |sed -nr 's/.* ([0-9]+)\..*/\1/p'`
return $VER
}
获取任意一块网卡的ip地址
get_ip(){
for nic in $*;do
#echo ${nic}的IP地址是:`ip addr show $nic 2> /dev/null |sed -nr 's/.* ([0-9.]+).* [0-9.]+ .*$/\1/p'`
RES=`ip addr show $nic 2> /dev/null|sed -nr 's/.* ([0-9.]+).* [0-9.]+ .*$/\1/p'`
#echo $RES
if [ -z "$RES" ];then
echo ${nic}不存在
else
echo ${nic}的IP地址是:`ip addr show $nic |sed -nr 's/.* ([0-9.]+).* [0-9.]+ .*$/\1/p'`
fi
done
}
打印绿色OK和红色FAILED
service_status(){
if [ $# -eq 0 ];then
echo "Usage: $0 service_name ..."
else
for service in $*;do
RES=`ls /usr/lib/systemd/system |grep $service.service`
if [ -z "$RES" ];then
action "$service服务没有安装" false
else
action $service的状态:`systemctl status $service |sed -nr '/active/s/[[:space:]]+Active: (\b\w+\b) .*/\1/p'` true
#STATUS=`systemctl status $service |sed -nr '/active/s/[[:space:]]+Active: (\b\w+\b) .*/\1/p'`
#echo $STATUS
fi
done
fi
#return $STATUS
}
start, stop, restart, status --模拟service
start(){
if [ ! -e /var/lock/subsys/$0 ];then
touch /var/lock/subsys/$0
action "启动成功" true
else
action "已经处于启动状态,无需处理" true
fi
}
stop(){
if [ ! -e /var/lock/subsys/$0 ];then
action "已经处于停止状态,无需处理" false
else
rm -rf /var/lock/subsys/$0
action "服务停止成功!" true
fi
}
restart(){
if [ ! -e /var/lock/subsys/$0 ];then
touch /var/lock/subsys/$0;action "启动成功" true
else
rm -rf /var/lock/subsys/$0;touch /var/lock/subsys/$0;action "重启成功" true
fi
}
status(){
if [ ! -e /var/lock/subsys/$0 ];then
action "服务停止状态" false
else
action "服务启动状态" true
fi
}
#未完待续...
标签:shell,service,lock,笔记,echo,else,Linux,action,subsys 来源: https://blog.51cto.com/13182370/2374597