# 格式 1
function_name() {
command1
command2
...
[return value]
}
# 格式 2(帶 function 關鍵字)
function function_name() {
commands...
}
demoFun。return n(0-255),省略則返回最後一條命令退出碼。調用後用 $? 獲取。#!/bin/bash
demoFun() {
echo "This is your first shell function!"
}
echo "Function begin..."
demoFun
echo "Function end!"
輸出:
Function begin...
This is your first shell function!
Function end!
#!/bin/bash
funWithReturn() {
echo "The function is to get the sum of two numbers..."
read -p "Input first number: " aNum
read -p "Input another number: " 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 !
$1~$9:第 1~9 個參數。${10}、${11}...:第 10 個及以上參數必須加大括號。$#:參數個數。$* / $@:所有參數列表。#!/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 !" # 錯誤:輸出 $1 後跟 0
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 11 !
The string of the parameters is 1 2 3 4 5 6 7 8 9 34 73 !
| 變量 | 含義 |
|---|---|
| $0 | 腳本名稱 |
| $1-$9 | 第 1-9 個參數 |
| ${10}... | 第 10+ 個參數 |
| $# | 參數總數 |
| $* | 所有參數(單字符串) |
| $@ | 所有參數(分離字符串) |
| $? | 上一命令/函數返回碼 |
| $$ | 當前進程 PID |
calculate_sum),避免與系統命令衝突。if [ $# -lt 2 ]; then echo "Usage..."; return 1; fi。local var=value 防止汙染全局環境。if func; then ... 判斷。Shell 函數讓腳本模塊化、可復用。掌握定義順序、參數獲取(注意 ${n})、返回值語義,即可編寫結構清晰的自動化腳本。