linux教程:shell脚本中如何使用函数

2025-10-20 14:52:45

1、没有参数的函数

func()

{

    echo "hello world"

}

func

linux教程:shell脚本中如何使用函数

2、有参数的写法,其中$1,$2就是参数。

func()

{

    echo "hello world"

    echo "arg1"$1;

    echo "arg2"$2

}

func "  a1" "  a2"

linux教程:shell脚本中如何使用函数

3、不定参数的函数可以这样写,参数的个数可以通过$#得到。

func()

{

    echo "hello world"

    echo "arg1"$1;

    echo "arg2"$2

    echo "arg number is:" $#

}

func "  a1"

linux教程:shell脚本中如何使用函数

4、调用其他文件中的函数:注意两个点之间有空格。

#test2.sh的内容和test1.sh完全相同。我只是拷贝了一份

. ./test2.sh

func “abc”“a”

linux教程:shell脚本中如何使用函数

5、两个函数名字相同,后面的函数会把前面的函数覆盖掉!

. ./test2.sh

func()

{

    echo "test.sh:func"$1

}

func "abc" "a"

linux教程:shell脚本中如何使用函数

6、如果函数是有返回值的。我们可以通过$?来获取返回值 

fun(){

    return `expr $1 + $2`

}

fun 1 2

echo $?

linux教程:shell脚本中如何使用函数

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢