Back
Featured image of post Shell函数

Shell函数

带你了解 shell 编程中函数的定义使用, 返回值, 变量的作用域, 以及如何导入自定义函数

函数定义与使用

语法格式

image-20231210165438966

image-20231210165425935

nginx 守护进程

#!/bin/bash
#

while true
do
    ps -ef | grep nginx | grep -v grep | grep -v $$ &> /dev/null

    if [ $? -eq 0 ]; then
        echo "nginx is running"
        sleep 3s
    else
        echo "nginx is stop, starting"
        systemctl start nginx
    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

函数返回值

  1. return
  2. echo

return 返回值案例

#!/bin/bash
#

function is_nginx_isrunning
{
	ps -ef | grep nginx | grep -v grep | grep $$ &> /dev/null
	
	if [ $? -eq 0 ]; then
		return
    else
    	return 1
	fi
}

is_nginx_running && echo "nginx is running" || echo "nginx is not running"

echo 返回值案例

#!/bin/bahs
#

function get_users
{
    users=`cat /etc/passwd | cut -d ":" -f1`

    echo $users
}

userlist=`get_users`

index=1
for u in ${userlist[@]}  # 也可以 $userlist
do
    echo "This is $index user: $u"
    index=$(($index+1))
done

全局变量与局部变量

Shell 中默认为全局变量

局部变量使用 local 关键字

#!/bin/bash
#

var1=1

function set_var2
{
    var2=2
}

echo $var1
echo $var2

set_var2

echo $var2

function set_var3
{
    local var3=3
}
set_var3
echo $var3

输出:

1

2

函数库

库文件通常以 .lib 结尾

base_function.lib

#!/bin/echo
# 提示不可运行

function  add
{
    echo "`expr $1 + $2`"
}

function divide
{
    echo "`expr $1 / $2`"
}

function sys_load
{
    echo "Memory Info"
    echo
    free -m

    echo
    echo "Disk Info"
    echo
    df -h
    echo
}

use_base_function.sh

#!/bin/bash
#

. /root/shell/base_function.lib    # 也可以用 source; 要用绝对路径

add 1 2

divide 7 3

sys_load