定义函数
两种定义格式
# 1.
name()
{
方法体
}
# 2.
function name
{
方法体
}
调用函数
- 直接使用函数名调用
- 函数内部可以直接使用参数 $1、$2…$n 来接收传入的参数
需求描述:写一个监控 nginx 的脚本;如果 Nginx 服务宕掉,则脚本可以检测到并将进程启动
#!bin/bash
#
this_pid=$$
while true
do
ps -ef | grep nginx | grep -v grep | grep -v $this_pid &> /dev/null
if [ $? -eq 0 ];then
echo "nginx is well!"
sleep 3
else
echo "nginx is down,staring..."
systemctl start nginx
sleep 3
fi
done
$$ 输出执行脚本过程所产生的子进程pid,因为如果脚本名字中 nginx 也会 grep 出来
向函数传递参数
需求描述:写一个脚本,该脚本可以实现计算器的功能,可以进行 +-*/ 四种计算,
例如:sh calcaulate.sh 30 + 40
sh calcaulate.sh 30 – 40
#!bin/bash
#
function calcu
{
case $2 in
+)
echo "`expr $1 + $3`"
;;
-)
echo "`expr $1 - $3`"
;;
\*)
echo "`expr $1 \* $3`"
;;
/)
echo "`expr $1 / $3`"
;;
*)
echo "error input"
;;
esac
}
calcu $1 $2 $3
函数返回值
- return
- 只能返回 1-255 整数,通常只是用来供其他地方调用获取状态,因此通常仅返回 0 或 1(0 表示成功,1 表示失败)
- echo
- 可以返回任何字符串结果,比如一个字符串或者列表值
return 一般用法
#!bin/bash
#
this_pid=$$
function is_nginx_running
{
ps -ef | grep nginx | grep -v grep |grep -v $this_pid &> /dev/null
if [ $? -eq 0 ];then
return
else
return 1
fi
}
is_nginx_running && echo "Nginx is running" || echo "Nginx is stop"
echo 一般用法
#!bin/bash
#
function get_users
{
users=`cat /etc/passwd | cut -d ":" -f 1`
echo $users
}
user_list=`get_users`
index=1
for u in $user_list
do
echo "The $index user is $u"
index=$(($index+1))
done
全局变量
- 不做特殊声明,Shell 中变量都是全局变量
- Tips:大型脚本程序中函数中慎用全局变量
局部变量
- 定义函数时,使用 local 关键字
- 函数内和外若存在同名变量,则函数内部变量覆盖外部变量
函数库
- 经常使用的重复代码封装成函数文件
- 一般不直接执行,而是由其他脚本调用
定义一个函数库,该函数库实现以下几个函数:
- 加法函数 add
- 减法函数 reduce
- 乘法函数 multiple
- 除法函数 divide
- 打印系统运行情况的函数 sys_load,该函数可以显示内存运行情况,
#!bin/bash
#
function add
{
echo "`expr $1 + $2`"
}
function reduce
{
echo "`expr $1 - $2 `"
}
function multiple
{
echo "`expr $1 \* $2`"
}
function divide
{
echo "`expr $1 / $2`"
}
function sys_load
{
echo "Monory Info"
echo
free -m
echo
echo "Disk usage"
echo
df -h
echo
}
.base_function 引用函数或者
绝对路径/base_funciton
经验之谈
- 库文件名的后缀是任意的,但一般使用.lib
- 库文件通常没有可执行选项
- 库文件无需和脚本在同级目录,只需在脚本中引用时指定
- 第一行一般使用#!/bin/echo,输出警告信息,避免用户执行