美文网首页
Linux--创建函数

Linux--创建函数

作者: Zee_李海海 | 来源:发表于2021-03-12 13:19 被阅读0次

    基本函数

    在开始编写较复杂的shell脚本时,你会发现自己重复使用了部分能够执行特定任务的代码。这些代码有时很简单,比如显示一条文本消息,或者从脚本用户那里获得一个答案;有时则会比较复杂,需要作为大型处理过程中的一部分被多次使用。
    在后一类情况下,在脚本中一遍又一遍地编写同样的代码会很烦人。如果能只写一次,随后在脚本中可多次引用这部分代码就好了。
    bash shell提供了这种功能。函数是一个脚本代码块,你可以为其命名并在代码中任何位置重用。要在脚本中使用该代码块时,只要使用所起的函数名就行了(这个过程称为调用函数)。

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

    第一种格式

    function name ( ) {
      commands
    }
    #name属性定义了赋予函数的唯一名称。脚本中定义的每个函数都必须有一个唯一的名称。
    #commands是构成函数的一条或多条bash shell命令。在调用该函数时,bash shell会按命令在函数中出现的顺序依次执行,就像在普通脚本中一样。
    

    第二种格式

    names( )  {
      commands
    }
    

    注意:函数调用要在函数定义之后

    例子

    第一种格式

    vi test.sh
    #!/bin/bash
    #using a function in a script
    function 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"
    
    sh test.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
    

    第二种格式

    vi test.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"
    
    sh test.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
    

    相关文章

      网友评论

          本文标题:Linux--创建函数

          本文链接:https://www.haomeiwen.com/subject/metzqltx.html