函數可以讓我們將一個複雜功能劃分成若干模塊,讓程序結構更加清晰,代碼重複利用率更高。
Shell 函數必須先定義後使用。
1、Shell 函數的定義格式
function_name () {
list of commands
[ return value ]
}
如果你願意,也可以在函數名前加上關鍵字 function:
function function_name () {
list of commands
[ return value ]
}
注意:
- 函數返回值,可以顯式增加return語句;如果不加,會將最後一條命令運行結果作爲返回值。
- Shell 函數返回值只能是整數,一般用來表示函數執行成功與否,0表示成功,其他值表示失敗。
- 如果 return 其他數據,比如一個字符串,往往會得到錯誤提示:“numeric argument required”。
2、函數返回字符串的技巧
如果一定要讓函數返回字符串,那麼可以先定義一個變量,用來接收函數的計算結果,腳本在需要的時候訪問這個變量來獲得函數返回值。
#!/bin/bash
# Define your function here
Hello () {
echo "Url is http://see.xidian.edu.cn/cpp/shell/"
}
# Invoke your function
Hello
調用函數只需要給出函數名,不需要加括號。
一個帶有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
# Capture value returnd by last command
ret=$?
echo "The sum of two numbers is $ret !"
$? 可以獲取上一個命令的退出狀態,在這裏也就是函數funWithReturn最後退出狀態。
3、函數嵌套
#!/bin/bash
# Calling one function from another
number_one () {
echo "Url_1 is http://see.xidian.edu.cn/cpp/shell/"
number_two
}
number_two () {
echo "Url_2 is http://see.xidian.edu.cn/cpp/u/xitong/"
}
number_one
腳本直接調用number_one,在number_one中調用number_two
運行結果:
Url_1 is http://see.xidian.edu.cn/cpp/shell/
Url_2 is http://see.xidian.edu.cn/cpp/u/xitong/
4、刪除函數
像刪除變量一樣,刪除函數也可以使用 unset 命令,不過要加上 .f 選項,如下所示:
$unset .f function_name
如果你希望直接從終端調用函數,可以將函數定義在主目錄下的 .profile 文件,這樣每次登錄後,在命令提示符後面輸入函數名字就可以立即調用。
5、帶參數函數
在Shell中,調用函數時可以向其傳遞參數。
在函數體內部,通過
帶參數的函數示例:
#!/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 !"
注意,
6、幾個特殊變量用來處理參數
特殊變量 說明
- $# 傳遞給函數的參數個數。
- $* 顯示所有傳遞給函數的參數。
- $@ 與 (2)相同,但是略有區別,請查看Shell特殊變量。
- $? 函數的返回值。