函式是讓腳本從「能跑」變成「好維護」的關鍵。以下依書中脈絡整理。
兩種寫法都可以:
function name {
commands
}
name() {
commands
}
若先後定義同名函式,後者會直接覆蓋前者,且不會有任何提示。
函式必須先定義再使用,像 shell 逐行解讀的特性使然。
#!/bin/bash
f1() { echo "this is f1."; }
f1
function f1 { echo "this is f1111."; }
f1
f2 # 此時 f2 尚未定義,會失敗
f2() { echo "this is f2."; }
$ function_test this is f1. this is f1111. ./function_test: line 12: f2: command not found
bash 把函式當小型腳本,結束時會回傳一個退出狀態碼,可用 $? 取得。三種產生方式:
預設值:取函式中最後一條指令的狀態碼,這其實很危險:
fun(){ ls nothing; echo $?; echo "done"; }
fun
echo "fun:$?"
ls 失敗回 2,但最後的 echo 成功,所以 fun 回 0。
return:明確指定 0~255 的整數作為退出碼。
函式輸出:把 stdout 存進變數,例如 result=`f1`。
腳本中定義的變數都是全域的,函式內可讀可寫:
var=1
fun(){ echo "var:"$var; var2=2; }
fun
echo "var2:"$var2
加上 local 就能宣告函式內部的區域變數,外部無法存取。
傳陣列要拆解成多個參數,在函式內再重組:
array=(a b c d)
fun(){ newarray=($@); echo ${newarray[*]}; echo ${newarray[3]}; }
fun ${array[*]}
若直接寫 fun $array,函式只會收到第一個元素。
回傳陣列則是依序 echo 再用括號包住:
fun(){ local array=(a b c d); echo ${array[*]}; }
array=(`fun`)
echo ${array[2]}
fun(){
local result=1
if [ $1 -eq 1 ]; then
echo 1
else
result=$[$1 * `fun $[$1 - 1]`]
echo $result
fi
}
fun $1
用反引號呼叫時,函式內的 echo 不會印到 stdout,而是成為回傳值。
source(等同點運算子 .)會在當前 shell 上下文中執行指令,而非另開子 shell,因此適合用來載入函式庫:
# lib_test
plus(){
if [ $# -ne 2 ]; then
echo "I need 2 numbers!"
return
fi
echo $[$1 + $2]
}
#!/bin/bash . lib_test plus $1 $2
$ plus(){ echo $[$1 + $2]; }
$ plus 3 1
4
換行寫法更清爽,不必分號:
$ plus(){
> echo $[$1 + $2]
> }
也可以寫進 .bashrc(存檔後執行 source ~/.bashrc 立即生效),或用 source 載入外部函式庫,後者更好維護。