鍍金池/ 教程/ Linux/ Shell 函數(shù)參數(shù)
Shell 特殊變量:Shell $0, $#, $*, $@, $?, $$和命令行參數(shù)
Shell 文件包含
Shell 輸入輸出重定向:Shell Here Document,/dev/null
Shell 函數(shù)參數(shù)
Shell 簡介
Shell printf命令:格式化輸出語句
第一個(gè) Shell 腳本
Shell echo 命令
Shell 運(yùn)算符:Shell 算數(shù)運(yùn)算符、關(guān)系運(yùn)算符、布爾運(yùn)算符、字符串運(yùn)算符等
Shell 數(shù)組:shell 數(shù)組的定義、數(shù)組長度
Shell until 循環(huán)
Shell if else 語句
Shell 變量:Shell 變量的定義、刪除變量、只讀變量、變量類型
Shell 字符串
Shell 與編譯型語言的差異
Shell 函數(shù):Shell 函數(shù)返回值、刪除函數(shù)、在終端調(diào)用函數(shù)
Shell 替換
Shell case esac 語句
Shell for 循環(huán)
什么時(shí)候使用 Shell
Shell 注釋
幾種常見的 Shell
Shell while 循環(huán)
Shell break 和 continue 命令

Shell 函數(shù)參數(shù)

在 Shell中,調(diào)用函數(shù)時(shí)可以向其傳遞參數(shù)。在函數(shù)體內(nèi)部,通過 $n 的形式來獲取參數(shù)的值,例如,$1 表示第一個(gè)參數(shù),$2 表示第二個(gè)參數(shù)...

帶參數(shù)的函數(shù)示例:

#!/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 $# !"  # 參數(shù)個(gè)數(shù)
    echo "The string of the parameters is $* !"  # 傳遞給函數(shù)的所有參數(shù)
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73

運(yùn)行腳本:

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 不能獲取第十個(gè)參數(shù),獲取第十個(gè)參數(shù)需要 ${10}。當(dāng) n>=10 時(shí),需要使用 ${n} 來獲取參數(shù)。

另外,還有幾個(gè)特殊變量用來處理參數(shù),前面已經(jīng)提到:

特殊變量 說明
$# 傳遞給函數(shù)的參數(shù)個(gè)數(shù)。
$* 顯示所有傳遞給函數(shù)的參數(shù)。
$@ 與 $* 相同,但是略有區(qū)別,請查看 Shell 特殊變量。
$? 函數(shù)的返回值。