您好,欢迎来到保捱科技网。
搜索
您的当前位置:首页shell ---创建函数

shell ---创建函数

来源:保捱科技网

创建函数

 

有两种格式可以用来在 bash shell 脚本中创建函数。

第一种格式采用关键字 function,后跟分配给该代码块的函数名。

function name {
    commands
}

name 属性定义了赋予函数的唯一名称。脚本中定义的每个函数都必须有一个唯一的名称。

commands 是构成函数的一条或多条 bash shell 命令。在调用该函数时,bash shell 会按命令在函数中出现的顺序依次执行,就行在普通脚本中一样。

在 bash shell 脚本中定义函数的第二种格式更接近于其他编程语言中定义函数的方式。

name() {
commands
}

使用函数

test1.sh

#!/bin/bash
#using a function in a script

func1() {
    echo "This is an example of a function"
}

count=1
while [ $count -le 5 ]
do
    func1
    count=$[ $count + 1 ]
done

echo "This is the end of the loop"
func1
echo "Now this is the end of the script"

运行结果:

mary@DESKTOP-2PJF7EM:~/mine/learning$ ./test1.sh 
This is an example of a function
This is an example of a function
This is an example of a function
This is an example of a function
This is an example of a function
This is the end of the loop
This is an example of a function
Now this is the end of the script

返回值

默认退出状态码

默认情况下,函数的退出状态码是函数中最后一条命令返回的退出状态码。

 

 

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- baoaiwan.cn 版权所有 赣ICP备2024042794号-3

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务