一、函數定義和調用
函數是Shell腳本中自定義的一系列執行指令,一般來說函數應該設定有傳回值(正确傳回0,錯誤傳回非0)。對于錯誤傳回,可以定義其他非0正值來細化錯誤。使用函數最大的好處是可避免出現大量重複代碼,同時增強了腳本的可讀性:如果你在某個Shell腳本中看到checkFileExist的這樣的代碼(實際是函數調用),一定不難猜出代碼的作用。
[root@Cfhost-170820-UCNK ~]# cat sayHello.sh
#!/bin/bash
function sayHello(){ #關鍵字function 可以省略
echo "Hello"
}
echo "Call function sayHello" #提示函數調用
sayHello #函數調用
[root@Cfhost-170820-UCNK ~]# sh sayHello.sh
Call function sayHello
Hello
[root@Cfhost-170820-UCNK ~]# cat countLine.sh
FILE=/etc/passwd
function countLine(){
local i=0
while read line
do
let ++i
done < $FILE
echo "$FILE have $i line"
echo "Call functino countLine"
countLine
[root@Cfhost-170820-UCNK ~]# sh countLine.sh
Call functino countLine
/etc/passwd have 25 line
二、函數的傳回值
函數的傳回值又叫函數的退出狀态,實際上是一種通信方式。Shell中的函數可以使用"傳回值"的方式來給調用者回報資訊(使用return關鍵字),不要忘了擷取上一個指令傳回值的方式是使用$? 這樣擷取函數傳回值的主要方式。
[root@Cfhost-170820-UCNK ~]# cat checkFileExist.sh
FILE=/etc/notExistFile #定義一個不存在的檔案
function checkFileExist(){ #定義checkFileExist函數
if [ -f $FILE ];then
return 0
else
return 1
fi
checkFileExist #調用函數
if [ $? -eq 0 ];then
echo "$FILE exist"
else
echo "$FILE not exist"
fi
[root@Cfhost-170820-UCNK ~]# sh checkFileExist.sh
/etc/notExistFile not exist
三、帶參數的函數
checkFileExist.sh腳本中定義了checkFileExist函數,但是可以看到這個腳本實際上寫死了FILE變量,這會造成想要判斷不同的檔案是否存在時,需要修改腳本中的FILE變量 -也就是要對代碼本身的内容進行修改,這也是典型的代碼和資料沒有分開而導緻的問題。事實上,可以通過定義帶參數的函數解決這個問題。
[root@Cfhost-170820-UCNK ~]# cat checkFileExist_v2.sh
function checkFileExist(){
if [ -f $1 ];then
echo "Call function checkFileExist"
checkFileExist $1
echo "$1 exist"
echo "$1 not exist"
執行結果:
[root@Cfhost-170820-UCNK ~]# sh checkFileExist_v2.sh /etc/not
Call function checkFileExist
/etc/not not exist
四、指定位置參數值
除了在腳本運作時給腳本傳入的位置參數外,還可以使用内置指令set指令給腳本指定位置參數的值(又叫重置)。一旦使用set設定了傳入參數的值,腳本将忽略運作時傳入的位置參數(實際上被set指令重置了位置參數的值)
set 1 2 3 4 5 6
COUNT=1
for i in $@
do
echo "Here \$ $COUNT is $i"
let "COUNT++"
done
執行結果如下:
[root@Cfhost-170820-UCNK ~]# sh set01.sh a b c d e f
Here $ 1 is 1
Here $ 2 is 2
Here $ 3 is 3
Here $ 4 is 4
Here $ 5 is 5
Here $ 6 is 6
五、移動位置參數
在shell中使用shift指令移動位置參數,shift指令可讓位置參數左邊移動一位
[root@Cfhost-170820-UCNK ~]# cat shift_03.sh
until [ $# -eq 0 ]
echo "Now \$1 is: $1, total parameter is:$#"
shift
[root@Cfhost-170820-UCNK ~]# sh shift_03.sh a b c
Now $1 is: a, total parameter is:3
Now $1 is: b, total parameter is:2
Now $1 is: c, total parameter is:1
利用shift計算腳本中所有參數的和:
[root@Cfhost-170820-UCNK ~]# cat shift_04.sh
TOTAL=0
let "TOTAL=TOTAL+$1"
echo $TOTAL
[root@Cfhost-170820-UCNK ~]# sh shift_04.sh 10 20 30
60