函数

2019-10-14  本文已影响0人  亮仔_c1b5

shell函数
函数介绍
函数语法
函数应用
一、函数介绍
在写代码的时候,我们很多人习惯从头写到结束,完成以后在一起测试。但是到测试阶段才发现:错误一大堆,上帝啊!弄死我吧!

为了解决这个问题,建议大家把代码模块化,一个模块实现一个功能,哪怕是一个很小的功能都可以,这样的话我们写代码就会逻辑上比较简单,代码量比较少,排错简单,这也就是函数的好处。

函数的优点:

代码模块化,调用方便,节省内存
代码模块化,代码量少,排错简单
代码模块化,可以改变代码的执行顺序
二、函数的语法
语法一:

函数名 () {
代码块
return N
}

语法二:
function 函数名 {
代码块
return N
}
三、函数的应用
定义一个函数

print () {
echo "welcome to ayitula"
或者

function hello {
echo "hello world"
}

hello就是函数名
print 和 hello就是函数的名字,函数名字命名参考变量一节中的变量命名规则

函数调用

定义好函数后,如果想调用该函数,只需通过函数名调用即可。

函数演示案例

!/bin/bash

N1 () {
echo "date +%F"
}

N2 () {
echo -e "\t\t\t\twelcome to ayitula"
echo -e "\n"
}

N3 () {
echo "1) 剪子"
echo "2) 石头"
echo "3) 布"
}

N4 () {
echo -e "\n\n\n"
read -p "请输入代码: " DL
}

方便调整代码执行顺序

N2

代码重复调用

N1
N1
N3
N4

输出

[root@www ~]# sh x2
welcome to ayitula

2019-02-19
2019-02-19

  1. 剪子
  2. 石头

请输入代码: 1

job:

案例一、nginx启动管理脚本

!/bin/bash

ngingx service manager scripts

=====================variables

nginxdoc="/usr/local/nginx"
nginxd="nginxdoc/sbin/nginx" pid="nginxdoc/logs/nginx.pid"
conf="$nginxdoc/conf/nginx.conf"

====================function

mystart () {
if [ -f pid ] && pstree -p |grep `catpid` &>/dev/null;then
echo "nginx already run..."
exit 0
else
if $nginxd ;then
echo -e "nginx start\t\t\t\t[\033[32m OK \033[0m]"
else
echo -e "nginx start\t\t\t\t[\033[31m FAIL \033[0m]"
fi
fi
}

mystop () {
if [ -f pid ] && pstree -p |grep `catpid` &>/dev/null;then
if killall -s QUIT $nginxd;then
echo -e "nginx stop\t\t\t\t[\033[32m OK \033[0m]"
else
echo -e "nginx stop\t\t\t\t[\033[31m FAIL \033[0m]"
fi
else
echo "nginx already stop...."
fi
}

myrestart () {
mystop;sleep 2 ;mystart
}

myreload () {
if [ -f pid ] && pstree -p |grep `catpid` &>/dev/null;then
if killall -s HUP $nginxd;then
echo -e "nginx reload\t\t\t\t[\033[32m OK \033[0m]"
else
echo -e "nginx reload\t\t\t\t[\033[31m FAIL \033[0m]"
fi
else
echo "nginx is stop...."
fi

}

mystatus () {
if [ -f pid ] && pstree -p |grep `catpid` &>/dev/null;then
echo "nginx is open"
else
echo "nginx is stop"
fi
}

===================main

calld function

case $1 in
start|START)
mystart
;;
stop) mystop ;;
restart) myrestart ;;
reload) myreload ;;
status) mystatus ;;
esac

上一篇下一篇

猜你喜欢

热点阅读