1. 程式人生 > >shell指令碼——函式(一)

shell指令碼——函式(一)

一.建立函式

  有兩種格式可以用來在bash shell指令碼中建立函式.

  第一種採用關鍵字function。後跟分配給該程式碼的函式名。

    function name {

     commands

    }

    name屬性定義了賦予函式唯一的名稱。指令碼中定義的每個函式都必須有一個唯一的名稱。

    commands是構成函式的一條或多條bash shell命令。在呼叫該函式時,bash shell會按命令在函式中出現的順序依次執行,就像在普通指令碼中一樣。

    在bash shell指令碼中定義函式的第二種格式更接近於其他程式語言中定義函式的方式。

    name(){

    conmmands

    }

    函式名後的空括號表明正在定義的是一個函式。這種格式的命名規則和之前定義shell指令碼函式的格式一樣。

二.使用函式

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

function func1 {
    echo "This is a function!"
}

count=1
while [ $count -le 5 ]

do 
    func1
    echo "This is:"$count
    count=$[ $count+1 ]
done

echo "This is the end of loop"

執行程式:

./function1.sh 

This is a function!
This is:1
This is a function!
This is:2
This is a function!
This is:3
This is a function!
This is:4
This is a function!
This is:5
This is the end of loop