一、函数介绍
1、函数:可以把代码模块化,一个模块实现一个功能。
2、函数优点:
代码模块化,调用方便,节省内存。
代码模块化,代码量少,排错简单。
代码模块化,可以改变代码的执行顺序。
3、函数执行:
函数默认不会执行,调用后才会执行。
调用方式:
脚本里输入函数名
调用特点:
可以重复调用
可以位置互换调用
二、函数的语法:
语法一:
#定义函数
函数名 () {
代码块
return #返回一个内容,例如执行成功返回一个内容。在C语言常用,shell中不常用。
}
#调用函数
函数名
语法二:
#定义函数
function 函数名 {
代码块
}
#调用函数
三、函数实践:
例:nginx服务管理 (利用function、case书写脚本)
#!/bin/bash
#Author: Liu xuelu
#email: bj_liuxuelu@163.com
#date: 2020-06-07
#Script Description:nginx service manage script
#call function and case
#==================================
#variables(定义变量)
ngnix_install_d=/usr/local/nginx #nginx安装目录
nginxd=$ngnix_install_d/sbin/nginx #nginx命令执行
pid_file=$ngnix_install_d/logs/nginx.pid #nginx进程id文件
# Source function library (源函数库)
if [ -f /etc/init.d/functions ];then
. /etc/init.d/functions
else
echo "not found /etc/init.d/functions "
exit
fi
if [ -f $pid_file ];then
nginx_process_id=`cat $pid_file `
nginx_process_num=$(ps aux|grep $nginx_process_id|grep -v "grep"|wc -l)
fi
#function (函数)
start ( ) {
if [ -f $pid_file ]&&[ $nginx_process_num -ge 1 ];then
echo "nginx running"
else
if [ -f $pid_file ]&&[ $nginx_process_num -lt 1 ];then
rm -f $pid_file #删除pid文件
echo "nginx start `daemon $nginxd`" #启动nginx服务,daemon为程序启动函数
exit #执行完退出脚本
fi
echo "nginx start `daemon $nginxd`" #启动nginx
#action "nginx start" $nginxd #另一种启动nginx方法
fi
}
stop () {
if [ -f $pid_file ]&&[ $nginx_process_num -ge 1 ];then
action "nginx stop" killall -s QUIT nginx
else
action "nginx stop" killall -s QUIT nginx &>/dev/null
fi
}
restart () {
stop
sleep 2
start
}
reload () {
if [ -f $pid_file ]&&[ $nginx_process_num -ge 1 ];then
action "nginx reload" killall -s HUP nginx
else
action "nginx reload" killall -s HUP nginx &>/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
;;
status )
status
;;
restart )
restart
;;
reload )
reload
;;
* )
echo "USAGE: $0 start|stop|restart|reload|status"
;;
esac
验证:
[root@www-nginx /server/scripts]# sh nginxd_1.sh start
nginx running
[root@www-nginx /server/scripts]# sh nginxd_1.sh stop
nginx stop [ 确定 ]
[root@www-nginx /server/scripts]# sh nginxd_1.sh restart
nginx start [ 确定 ]
[root@www-nginx /server/scripts]# sh nginxd_1.sh restart
nginx stop [ 确定 ]
nginx start [ 确定 ]
[root@www-nginx /server/scripts]# sh nginxd_1.sh status
nginx running
[root@www-nginx /server/scripts]# sh nginxd_1.sh reload
nginx reload [ 确定 ]
[root@www-nginx /server/scripts]#