国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > Linux Shell > 正文

Shell腳本函數定義和函數參數

2020-07-27 19:14:42
字體:
來源:轉載
供稿:網友

一、Shell函數

本教程目前為止所有腳本都是從頭到尾執行。這樣做很好,但你也許已經注意到有些腳本段間互相重復。

shell允許將一組命令集或語句形成一個可用塊,這些塊稱為shell函數。

shell中函數的定義格式如下:

復制代碼 代碼如下:
函數名(){
    command1
    command2
    ...
    commandN
    [ return value ]
}

如果愿意,可在函數名前加上關鍵字function,這取決于使用者。

復制代碼 代碼如下:
function 函數名(){
    command1
    command2
    ...
    commandN
    [ return value ]
}

函數返回值,可以顯示增加return語句;如果不加,則將最后一條命令運行結果作為返回值(一般為0,如果執行失敗則返回錯誤代碼)。 return后跟數值(0-255)。

函數可以放在同一個文件中作為一段代碼,也可以放在只包含函數的單獨文件中。函數不必包含很多語句或命令,甚至可以只包含一個echo語句,這取決于使用者。

下面的例子定義了一個函數并進行調用:

復制代碼 代碼如下:

#!/bin/bash
demoFun(){
    echo "This is your first shell function!"
}
echo "Function begin..."
hello
echo "Function end!"

輸出:
Function begin...
This is your first shell function!
Function end!

下面定義一個帶有return語句的函數:

復制代碼 代碼如下:

#!/bin/bash
funWithReturn(){
    echo "The function is to get the sum of two numbers..."
    echo -n "Input first number: "
    read aNum
    echo -n "Input another number: "
    read anotherNum
    echo "The two numbers are $aNum and $anotherNum !"
    return $(($aNum+$anotherNum))
}
funWithReturn
echo "The sum of two numbers is $? !"

輸出類似下面:
The function is to get the sum of two numbers...
Input first number: 25
Input another number: 50
The two numbers are 25 and 50 !
The sum of two numbers is 75 !

函數返回值在調用該函數后通過 $? 來獲得。

注意:所有函數在使用前必須定義。這意味著必須將函數放在腳本開始部分,直至shell解釋器首次發現它時,才可以使用。調用函數僅使用其函數名即可。

二、Shell函數參數

在Shell中,調用函數時可以向其傳遞參數。在函數體內部,通過 $n 的形式來獲取參數的值,例如,$1表示第一個參數,$2表示第二個參數...

帶參數的函數示例:

復制代碼 代碼如下:

#!/bin/bash
funWithParam(){
    echo "The value of the first parameter is $1 !"
    echo "The value of the second parameter is $2 !"
    echo "The value of the tenth parameter is $10 !"
    echo "The value of the tenth parameter is ${10} !"
    echo "The value of the eleventh parameter is ${11} !"
    echo "The amount of the parameters is $# !"
    echo "The string of the parameters is $* !"
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73

輸出:
The value of the first parameter is 1 !
The value of the second parameter is 2 !
The value of the tenth parameter is 10 !
The value of the tenth parameter is 34 !
The value of the eleventh parameter is 73 !
The amount of the parameters is 12 !
The string of the parameters is 1 2 3 4 5 6 7 8 9 34 73 !"

注意,$10 不能獲取第十個參數,獲取第十個參數需要${10}。當n>=10時,需要使用${n}來獲取參數。

另外,還有幾個特殊字符用來處理參數:

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 元谋县| 克什克腾旗| 登封市| 吴堡县| 肃宁县| 红河县| 吴旗县| 南安市| 千阳县| 裕民县| 梅河口市| 万宁市| 玛纳斯县| 大港区| 阳原县| 莲花县| 广宗县| 大厂| 霍山县| 博白县| 青田县| 中卫市| 郧西县| 察哈| 玉环县| 县级市| 孝昌县| 本溪| 思南县| 普宁市| 六安市| 丹寨县| 苏州市| 颍上县| 井研县| 象山县| 兴国县| 鹤山市| 安仁县| 松阳县| 城市|