shell中函数的使用方法

来源:互联网 发布:linux修改tomcat内存 编辑:程序博客网 时间:2024/05/16 03:41

shell函数

普通的函数

shell可以定义自己的函数,格式:

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

举个例子

Fun(){    echo "Hello world~"}echo "Function is start"Funecho "Function is end"

运行的结果:

Function is startHello world~Function is end

带有return的函数

如果添加返回,return语句

Fun(){    echo "Hello world~"    echo "please input a word >>"    read aWord    echo $aWord    return $aWord}echo "Function is start"Funecho "$? !"echo "Function is end"

在上面的程序的基础上有所改动,运行程序,显示的结果如下:

Function is startHello world~please input a word >>2   #选择输入222 !Function is end

带有参数的函数

在shell中,在调用函数的同时,也可以传递参数。

下面举一个带有参数的例子。

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

运行上面的程序,结果如下。

第一个参数为 1 !第二个参数为 2 !第十个参数为 10 !第十个参数为 34 !第十一个参数为 73 !参数总数有 11!作为一个字符串输出所有参数 1 2 3 4 5 6 7 8 9 34 73 !

注意:注意,10{10}。当n>=10时,需要使用${n}来获取参数。

本文参考:http://www.runoob.com/linux/linux-shell-func.html
https://www.shiyanlou.com/courses/944/labs/3570/document

原创粉丝点击