1. 程式人生 > >shell腳本從入門到復雜 其八(函數)

shell腳本從入門到復雜 其八(函數)

shell 函數

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

Shell的函數存在於內存,而不是硬盤文件,所以速度很快,另外,Shell還能對函數進行預處理,所以函數的啟動比腳本更快。


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


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

[ function ] funname [()]


{


action;


[return int;]


}


說明:

1、可以帶function fun() 定義,也可以直接fun() 定義,不帶任何參數。

2、參數返回,可以顯示加:return 返回,如果不加,將以最後一條命令運行結果,作為返回值。 return後跟數值n(0-255


案例:

簡單的函數調用

# vi function1.sh

#!/bin/bash

demoFun(){

echo "this is my first function"

}

echo "function is starting..."

demoFun

echo "function is over"


執行結果是:

function is starting...

this is my first function

function is over


返回值

函數中的關鍵字“return”可以放到函數體的任意位置,通常用於返回某些值,Shell在執行到return之後,就停止往下執行,返回到主程序的調用行,return的返回值只能是0~256之間的一個整數,返回值將保存到變量“$?”中。



案例:

返回兩個輸入數的和

# vi .sh function2.sh

#!/bin/bash

funreturn(){

echo "The function is used to add the two figures together..."

echo "Enter the first number: "

read num1

echo "Enter the second number: "

read num2

echo "The two number is $num1 and $num2"

return $(($num1+$num2))

}

funreurn

echo "The sum of the two number is $?"


執行結果

# sh function2.sh

The function is used to add the two figures together...

Enter the first number:

4

Enter the second number:

5

The two number is 4 and 5

The sum of the two number is 9


參數傳遞

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


案例:

# vi function3.sh

#!/bin/bash

funparam(){

echo "The first param $1"

echo "The second param $2"

echo "The ten param ${10}"

echo "The sum of the param $#"

echo "Output the all param with string format $*"

}

funparam 1 two 3 4 5 6 7 8 9 ak


執行結果:

# sh function3.sh

The first param 1

The second param two

The ten param ak

The sum of the param 10

Output the all param with string format 1 two 3 4 5 6 7 8 9 ak


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


補充說明:

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


shell腳本從入門到復雜 其八(函數)