首页 > 其他 > 详细

创建函数

时间:2019-05-01 10:15:32      阅读:105      评论:0      收藏:0      [点我收藏+]

  在shell脚本编写中,通常有很多处使用相同的代码。如果这些代码比较短小,name通常并不费事。但是,如果有打断代码需要重写,则会让人厌烦,这个我们就需要使用函数来处理;

1、基本脚本函数

  函数是被富裕名称的脚本代码块,可以在代码的任意位置重复使用。引用函数的过程,我们称之为调用;

  1.1、创建函数

    在bash shell脚本中创建函数可以使用两种格式:

function name {  #name为唯一名称
    commands    #commands为组成函数功能的命令
}

    另外一种格式

name() {
commands
}

  1.2、使用函数

    相应的函数名需要在脚本中指定

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

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

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"

    注意,不能在函数被定义之前去调用这个函数,会报错

#!/bin/bash
# using a function located in the middle of a script

count=1
echo "This line comes before the function definition"

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

while [ $count -le 5 ]
do
    func1
    count=$[ $count + 1 ]
done
echo "This is the end of the loop"
func2  #没有定义func2,所以这里会报错
echo "Now this is the end of the script"

    函数的命名也需要注意,必须唯一。如果重新定义了函数,则新定义的函数就会覆盖原来的函数

#!/bin/bash
# testing using a duplicate function name

function func1 {
    echo "This is first definition of the function name"
}

func1

function func1 {  #新定义的函数就会覆盖原来的函数
    echo "This is a repeat of the same function name"
}

func1
echo "This is the end of the script"

2、返回值

  bash shell将函数看成小型的脚本,并以退出转态结束。函数退出转态有三种生成方式;

  2.1、默认退出状态

  2.2、使用return命令

  2.3、使用函数输出

3、在函数中使用变量

  3.1、向函数传递参数

  3.2、在函数中处理变量

4、数组变量与函数

  4.1、向函数传递数组

  4.2、从函数返回数组

5、函数递归

6、创建库

7、在命令行中使用函数

  7.1、在命令行创建函数

  7.2、在.bashrc文件中定义函数

创建函数

原文:https://www.cnblogs.com/BurnovBlog/p/10799057.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!