15.Shell函数 - morris131/morris-book GitHub Wiki

Shell函数

函数可以让我们将一个复杂功能划分成若干模块,让程序结构更加清晰,代码重复利用率更高。像其他编程语言一样,Shell 也支持函数。Shell 函数必须先定义后使用。 Shell 函数的定义格式如下:

[ function ] funname [()]
{
    action;
    [return int;]
}

可以带function fun() 定义,也可以直接fun() 定义,不带任何参数。

参数返回,可以显示加return返回,如果不加,将以最后一条命令运行结果,作为返回值。 return后跟数值n(0-255)。

简单使用

下面的例子定义了一个函数并进行调用:

#!/bin/bash

hello()
{
  echo "hello function"
}

echo "execute function start"
hello
echo "execute function end"
# chmod +x function.sh 
# ./function.sh 
execute function start
hello function
execute function end

调用函数只需要给出函数名,不需要加括号。

函数返回值

再来看一个带有return语句的函数:

#!/bin/bash
funWithReturn(){
    echo "The function is to get the sum of two numbers..."
    echo -n "Input first number: "
    read aNum
    echo -n "Input another number: "
    read anotherNum
    echo "The two numbers are $aNum and $anotherNum !"
    return $(($aNum+$anotherNum))
}
funWithReturn
# Capture value returnd by last command
ret=$?
echo "The sum of two numbers is $ret !"
# chmod +x functionReturn.sh
# ./functionReturn.sh 
The function is to get the sum of two numbers...
Input first number: 2
Input another number: 3
The two numbers are 2 and 3 !
The sum of two numbers is 5 !
# ./functionReturn.sh 
The function is to get the sum of two numbers...
Input first number: 200
Input another number: 300
The two numbers are 200 and 300 !
The sum of two numbers is 244 !

调用函数仅使用其函数名即可,函数返回值在调用该函数后通过 $? 来获得。

函数参数

在Shell中,调用函数时可以向其传递参数。在函数体内部,通过 $n 的形式来获取参数的值,例如,$1表示第一个参数,$2表示第二个参数...

下面是一个带参数的函数示例:

#!/bin/bash

funWithParam(){
    echo "第一个参数为 $1 !"
    echo "第二个参数为 $2 !"
    echo "第十个参数为 $10 !"
    echo "第十个参数为 ${10} !"
    echo "第十一个参数为 ${11} !"
    echo "参数总数有 $# 个!"
    echo "作为一个字符串输出所有参数 $* !"
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73
# chmod +x functionParam.sh 
# ./functionParam.sh 
第一个参数为 1 !
第二个参数为 2 !
第十个参数为 10 !
第十个参数为 34 !
第十一个参数为 73 !
参数总数有 11 个!
作为一个字符串输出所有参数 1 2 3 4 5 6 7 8 9 34 73 !

$10 不能获取第十个参数,获取第十个参数需要${10}。当n>=10时,需要使用${n}来获取参数。更多变量参考 linux:shell:传递参数#特殊变量列表

删除函数

像删除变量一样,删除函数也可以使用 unset 命令,不过要加上 -f 选项,如下所示:

# unset .f mpush
⚠️ **GitHub.com Fallback** ⚠️