編程學習網 > 編程教程 > Linux 教程
2015
09-06

Shell 函數

清華大佬耗費三個月吐血整理的幾百G的資源,免費分享!....>>>

Shell 函數

linux shell 可以用戶定義函數,然后在shell腳本中可以隨便調用。

shell中函數的定義格式如下:

[ function ] funname [()]

{

    action;

    [return int;]

}

說明:

  • 1、可以帶function fun() 定義,也可以直接fun() 定義,不帶任何參數。
  • 2、參數返回,可以顯示加:return 返回,如果不加,將以最后一條命令運行結果,作為返回值。 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!

下面定義一個帶有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
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 !

函數返回值在調用該函數后通過 $? 來獲得。

注意:所有函數在使用前必須定義。這意味著必須將函數放在腳本開始部分,直至shell解釋器首次發現它時,才可以使用。調用函數僅使用其函數名即可。


函數參數

在Shell中,調用函數時可以向其傳遞參數。在函數體內部,通過 $n 的形式來獲取參數的值,例如,$1表示第一個參數,$2表示第二個參數...

帶參數的函數示例:

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

注意,$10 不能獲取第十個參數,獲取第十個參數需要${10}。當n>=10時,需要使用${n}來獲取參數。

另外,還有幾個特殊字符用來處理參數:

參數處理 說明
$# 傳遞到腳本的參數個數
$* 以一個單字符串顯示所有向腳本傳遞的參數
$$ 腳本運行的當前進程ID號
$! 后臺運行的最后一個進程的ID號
$@ 與$*相同,但是使用時加引號,并在引號中返回每個參數。
$- 顯示Shell使用的當前選項,與set命令功能相同。
$? 顯示最后命令的退出狀態。0表示沒有錯誤,其他任何值表明有錯誤。

掃碼二維碼 獲取免費視頻學習資料

編程學習