Shell实战之函数的高级用法

335 阅读1分钟

函数定义和使用

#!/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=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
}