一:函数
函数默认不会执行,除非你调用
函数的优点:
1.代码模块化,调用方便,节省内存
2.代码模块化,代码量少,排错简单
3.代码模块化,可以改变代码的执行顺序
语法一:
函数名(){
代码块
return N
}
语法二:
function 函数名{
代码块
return N
}
二:函数的应用
【例:nginx启动管理脚本】
#variables
proc=nginx
nginx_install_doc=/usr/local/nginx
nginxd=$nginx_install_doc/sbin/nginx
pid_file=$nginx_install_doc/logs/nginx.pid
#Source function library
if [ -f /etc/init.d/functions ];then #/etc/init.d/functions系统自带的函数库
. /etc/init.d/functions
else
echo "not found file /etc/init.d/functions"
exit
fi
if [ -f $pid_file ];then
nginx_process_id=`cat $pid_file` #进程号ID ps aux |grep 进程号ID,如果有ID,则说明进程存在
nginx_process_num=`ps aux |grep $nginx_process_id|grep -v "grep"|wc -l` #ps aux |grep 进程号ID|grep -v "grep"|wc -l 不要grep那条,并统计
fi
#function
start () {
#如果Nginx没有启动直接启动,否则报错 已经启动
if [ -f $pid_file ]&&[ $nginx_process_num -ge 1 ];then
echo "nginx runnning......"
elif [ -f $pid_file ]&&[ $nginx_process_num -lt 1 ];then
rm -f $pid_file #正常情况下nginx退出会自动删掉pid_file文件
echo " nginx start `daemon $nginxd` " #daemon是/etc/init.d/functions中的方法,执行
else
echo " nginx start `daemon $nginxd` " #或者action "nginx start" $nginxd
fi
}
stop () {
if [ -f $pid_file ]&&[ $nginx_process_num -ge 1 ];then
action "nginx stop" killall -s QUIT $proc
rm -f $pid_file
else
action "nginx stop " killall -s QUIT $proc 2>/dev/null
fi
}
restart () {
stop
sleep 1
start
}
reload () {
if [ -f $pid_file ]&&[ $nginx_process_num -ge 1 ];then
action "nginx reload" killall -s HUP $proc
else
action "nginx reload" killall -s HUP $proc 2>/dev/null
fi
}
status () {
if [ -f $pid_file ]&&[ $nginx_process_num -ge 1 ];then
echo "nginx running......."
else
echo "nginx stop"
fi
}
#callable
case $1 in
start) start;;
stop) stop;;
restart) restart;;
reload) reload;;
status) status;;
*) echo "USAGE: $0 start|stop|restart|reload|status";;
esac
补充:
(1)sh -x 脚本名字,可以查看运行过程
(2)安装Killall
yum search killall(最下面有一个psmisc.x86_64)
yum -y install psmisc.x86_64
killall nginx