函数定义和使用
#!/bin/bash#实时监控nginx进程的状态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=1for u in $user_listdo echo "The $index user is : $u" index=$(($index+1))done复制代码
局部变量和全局变量
#!/bin/bash#var1="Hello world"function test{ local var2=87}testecho $var1echo $var2复制代码
函数库
#!/bin/bash#. /root/lesson/3.5/lib/base_functionadd 12 23reduce 90 30multiple 12 12divide 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}复制代码