-
函数的定义与使用
# 在终端中直接写定义和调用函数
[root@study shell-study]# test()
> {
> echo "test function"
> }
[root@study shell-study]# test
test function
脚本:检查nginx进程是否存在,若不存在则自动拉起该进程,并将该脚本变成守护进程
方法1
#!/bin/bash
#
while true
do
this_pid=$$ # $$返回当前脚本的pid
status=`ps -ef | grep nginx | grep -v grep | grep -v $this_pid`
if [ "$status" == 0 ];then
echo "Nginx is running well"
sleep 3
else
systemctl start nginx
echo "Nginx is down,Start it...."
fi
done
方法2
#!/bin/bash
#
while true
do
this_pid=$$ # $$返回当前脚本的pid,如果脚本名字带有nginx,也需要过滤掉
`ps -ef | grep nginx | grep -v grep | grep -v $this_pid &> /dev/null`
if [ $? -eq 0 ];then
echo "Nginx is running well"
sleep 3
else
systemctl start nginx
echo "Nginx is down,Start it...."
fi
done
说明:守护进程都是在后台运行,可以使用:nohup sh xxx.sh & 后台运行脚本
-
函数传递参数
[root@study shell-study]# function greeting
> {
> echo "Hello $1"
> }
[root@study shell-study]# greeting xiaoming
Hello xiaoming
[root@study shell-study]#
例子:
写一个脚本,该脚本可以实现计算器的功能,可以进行+-*/四种运算
#!/bin/bash
#
function calcu
{
case $2 in
+)
echo "`expr $1 + $3`"
;;
-)
echo "`expr $1 - $3`"
;;
\*)
echo "`expr $1 \* $3`"
;;
/)
echo "`expr $1 / $3`"
;;
esac
}
calcu $1 $2 $3
调用:sh xxx.sh 1 + 2
-
函数返回值
例子:
#!/bin/bash
#
this_pid=$$ # $$返回当前脚本的pid,如果脚本名字包含nginx,需要使用grep -v $$ 过滤
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 stoped"
#!/bin/bash
#
function get_users
{
users=`cat /etc/passwd | cut -d: -f1`
echo $users
}
user_list=`get_users`
index=1
for u in $user_list
do
echo "The $index user is : $u"
index=`expr $index + 1`
done
-
局部变量和全局变量
#!/bin/bash
#
var1="Hello World"
function test
{
var2=87
}
echo $var1
echo $var2
test
echo $var1
echo $var2
调用脚本:
[root@study shell-study]# sh test.sh
Hello World
Hello World
87
[root@study shell-study]#
#!/bin/bash
#
var1="Hello World"
function test
{
local var2=87
}
test
echo $var1
echo $var2
调用脚本输出:
[root@study shell-study]# sh test.sh
Hello World
[root@study shell-study]#
-
函数库
需求:定义一个函数库,该函数库实现以下几个函数:
1)加法函数add:add 12 89
2)减法函数reduce:reduce 80 20
3)乘法函数multiple:multiple 12 10
4)除法函数divide:divide 9 3
5)打印系统运行情况的函数sys_load,该函数可以显示内存运行情况,磁盘使用情况
库文件(后缀一般都是.lib):base_function.lib
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 "Memory Info"
echo
free -m
echo
echo "Disk Usage"
df -h
echo
}
脚本:calculate.sh
#!/bin/bash
#
. /root/base_function.lib #引用库文件
add 12 23
reduce 90 30
multiple 12 12
divide 12 2