函数定义和使用
#!/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 running well"
sleep 3
else
systemctl start nginx
echo "Nginx is down,Start it...."
fi
done
复制代码
向函数传递参数
#!/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
复制代码
函数返回值
#!/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 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=$(($index+1))
done
复制代码
局部变量和全局变量
#!/bin/bash
var1="Hello world"
function test
{
local var2=87
}
test
echo $var1
echo $var2
复制代码
函数库
#!/bin/bash
. /root/lesson/3.5/lib/base_function
add 12 23
reduce 90 30
multiple 12 12
divide 12 2
复制代码
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"
echo
df -h
echo
}
复制代码