shell 函数

1 shell函数的定义及其调用

shell函数有两种格式

function name {

    commands

}

name() {

    commands

}

其中,name为函数名,commands为函数体中执行的语句块。定义函数后,可以简单地通过函数名name对其进行调用。

注:

如果出现两个同名的函数定义,那么后者会覆盖前者,而不是报错。

2 函数返回值

shell函数在运行结束时返回状态码,有三种方式:

1 默认情况下,返回函数中最后一条命令的状态码,可以用$?来获取函数的退出状态码

#! /bin/bash
# testing the exit status of a function
#

function func1 {
        echo "This is the first form of defining a function:"
        ls -l badfile   # badfile is not exist
}

func2() {
        echo "This is the second form of defining a function:"
        date            #
}

echo "Testing the function and exit status"
echo
func1
echo "The exit status of func1 is: $?"
echo
func2
echo "The exit status of func2 is: $?"

[root@benxintuzi shell]# ./35.sh
Testing the function and exit status

This is the first form of defining a function:
ls: cannot access badfile: No such file or directory
The exit status of func1 is: 2

This is the second form of defining a function:
Tue Aug 11 22:43:48 PDT 2015
The exit status of func2 is: 0

2 使用return命令可以返回0~255之间的任意值

#! /bin/bash
# testing the exit status of a function
#

func() {
        read -p "Please enter a value: " value
        echo "doubling the input value..."
        return $[ $value * 2 ]
}

func
echo "The exit status of func is: $?"

[root@benxintuzi shell]# ./36.sh
Please enter a value: 50
doubling the input value...
The exit status of func is: 100
[root@benxintuzi shell]# ./36.sh
Please enter a value: 200
doubling the input value...
The exit status of func is: 144

3 使用变量保存,这种方式不仅可以返回任意数值,还可以返回字符串值

#! /bin/bash
# testing the exit status of a function
#

func() {
        read -p "Please enter a value: " value
        echo $[ $value * 2 ]
        echo "hello, I come"
}

result=`func`
echo "The exit status of func is: $result"

[root@benxintuzi shell]# ./37.sh
Please enter a value: 500
The exit status of func is: 1000
hello, I come

3 函数参数

函数可以利用标准的环境变量参数,$0表示函数名,$1表示第一个参数,$2表示第二个参数,...,$#表示参数个数。

#! /bin/bash
# access script parameters inside a function
#

func() {
        echo $[ $1 * $2 ]
}

if [ $# -eq 2 ]
then
        value=`func $1 $2`
        echo "The result is $value"
else
        echo "Usage: func a b"
fi

[root@benxintuzi shell]# ./38.sh 55 66
The result is 3630

4 函数变量

包括全局变量与局部变量。默认情况下,在shell中定义的任何变量都是全局变量。如果在变量定义前加上local关键字就变为局部变量了,如:local temp。

#! /bin/bash
# local and global variable
#

func() {
        local temp=$[ $value + 5 ]
        result=$[ $temp * 2 ]
}

value=10
temp=20
func

echo "$temp"
echo "$result"

[root@benxintuzi shell]# ./39.sh
20
30

5 数组变量

数组作为函数参数:

必须将数组变量分解为单个值,然后将这些值用作函数参数使用;在函数体中,可以将所有参数重组为新的数组变量:

#! /bin/bash
# array variable to function

func() {
        local newarray
        newarray=(`echo "$@"`)
        echo "The new array value is: ${newarray[*]}"

        local sum=0
        for value in ${newarray[*]}
        do
                sum=$[ $sum + $value ]
        done
        echo "The sum of newarray is: $sum"
}

myarray=(1 2 3 4 5)
echo "The original array is ${myarray[*]}"
func ${myarray[*]}

[root@benxintuzi shell]# ./41.sh
The original array is 1 2 3 4 5
The new array value is: 1 2 3 4 5
The sum of newarray is: 15

数组作为函数返回值:

#! /bin/bash
# function return array

func() {
        local oriarray
        local newarray
        local elements
        local i

        oriarray=(`echo "$@"`)
        newarray=(`echo "$@"`)
        elements=$[ $# - 1 ]

        for (( i = 0; i <= $elements; i++ ))
        {
                newarray[$i]=$[ ${oriarray[$i]} * 2 ]
        }
        echo ${newarray[*]}
}

myarray=(1 2 3 4 5)
echo "The original array is ${myarray[*]}"
arg1=`echo ${myarray[*]}`
result=(`func $arg1`)
echo "The new array is: ${result[*]}"

[root@benxintuzi shell]# ./42.sh
The original array is 1 2 3 4 5
The new array is: 2 4 6 8 10

6 创建库文件

函数库文件是为了解决不同脚本文件中使用相同函数块的问题。

首先定义一个库文件myfuncs用来解决四则运算功能:

[root@benxintuzi shell]# cat myfuncs 
# my script functions

addem() {
        echo $[ $1 + $2 ]
}

minusem() {
        echo $[ $1 - $2 ]
}

multiem() {
        echo $[ $1 * $2 ]
}

divem() {
        if [ $2 -eq 0 ]
        then
                -1
        else
                echo $[ $1 / $2 ]
        fi
}

然后在脚本文件中使用库文件中的函数即可,但是使用前必须使用source命令或者.命令在当前上下文环境中运行库文件:

[root@benxintuzi shell]# cat 40.sh
#! /bin/bash
# using functions defined in a library file

# excute library file in the context
. ./myfuncs     # source ./myfuncs

value1=10
value2=4

result1=`addem $value1 $value2`
result2=`minusem $value1 $value2`
result3=`multiem $value1 $value2`
result4=`divem $value1 $value2`

echo "addem($value1, $value2): $result1"
echo "minusem($value1, $value2): $result2"
echo "multiem($value1, $value2): $result3"
echo "divem($value1, $value2): $result4"

执行脚本文件:

[root@benxintuzi shell]# ./40.sh
addem(10, 4): 14
minusem(10, 4): 6
multiem(10, 4): 40
divem(10, 4): 2

7 在命令行中使用shell函数

方式一:

在命令行中直接定义一个函数:函数名及其函数体在一行内定义,不同语句之间用分号隔开:

[root@benxintuzi shell]# addem() { val1=5; val2=10; echo $[ val1 + $val2 ]; }
[root@benxintuzi shell]# addem
15

方式二:

在命令行中直接定义一个函数:函数名及其函数体在多行中定义,语句末尾不用加分号:

[root@benxintuzi shell]# addem() {
> val1=5
> val2=10
> echo $[ $val1 + $val2 ]
> }
[root@benxintuzi shell]# addem
15

方式三:

在.bashrc文件中定义函数:

在命令行中直接定义的shell函数在退出shell时就丢失了,如果想使得在每次启动新shell时都定义这个函数,一个比较好的办法就是将函数定义在.bashrc文件中。

原文地址:https://www.cnblogs.com/benxintuzi/p/4724710.html