首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Shell 腳本教程:函數定義、參數傳遞與返回值實戰

     編輯:Java 相關知識

Shell 函數基礎語法

# 格式 1
function_name() {
    command1
    command2
    ...
    [return value]
}

# 格式 2(帶 function 關鍵字)
function function_name() {
    commands...
}
  • 函數必須先定義後調用。
  • 調用直接寫函數名:demoFun。
  • 返回值:return n(0-255),省略則返回最後一條命令退出碼。調用後用 $? 獲取。

示例 1:無參無返回值

#!/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!

示例 2:帶返回值

#!/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 個及以上參數必須加大括號。
  • $#:參數個數。
  • $* / $@:所有參數列表。

示例 3:帶參數

#!/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

最佳實踐建議

  1. 函數命名用動詞+名詞(如 calculate_sum),避免與系統命令衝突。
  2. 參數檢查:if [ $# -lt 2 ]; then echo "Usage..."; return 1; fi。
  3. 局部變量用 local var=value 防止汙染全局環境。
  4. 返回值語義化:0=成功,非 0=失敗代碼,便於 if func; then ... 判斷。

總結

Shell 函數讓腳本模塊化、可復用。掌握定義順序、參數獲取(注意 ${n})、返回值語義,即可編寫結構清晰的自動化腳本。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved