能夠組織一些經常使用的方法,寫到函數裏面,做爲公共的方法方便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
}
#未完待續...