標籤:shell 函數
函數 定義: 1、無傳回值 #function為關鍵字,FUNCTION_NAME為函數名 function FUNCTION_NAME(){ command1 command2 ... } 省略關鍵字function,效果一樣 FUNCTION_NAME(){ command .... } 例: 1、簡單函式宣告和調用 #!/bin/bash function sayHello(){ echo "Hello World!" } sayHello 注意: 1、sayHello調用的時候沒有(),sayHello()這樣的調用會出錯。 2、如果先調用再聲明,則調用和聲明之間不能有其他語句 2、計算檔案的行數 #!/bin/bash if [[ $# -lt 1 ]];then echo "Please input a filename." return fi file=$1 countLine function countLine(){ local line=0 while read do let "line++"; done < $file echo "$file has $line lines." } 2、函數的傳回值 return 擷取傳回值的主要方式是$? 例: #檢測檔案是否存在 #!/bin/bash file=$1 check if [ $? -eq 0 ];then echo "$file exists." else echo "$file doesn‘t exist." fi function check(){ if [ -e $file ];then return 0 else return 1 fi } 3、帶參數的函數 1、位置參數 這個和進階語言不一樣,在函式宣告裡沒有指定參數,而是直接在函數體裡使用,調用的時候直接傳入參數即可 例: 1、檢測檔案是否存在 #!/bin/bash check $1 #這裡不再使用file變數 if [ $? -eq 0 ];then echo "$1 exists." else echo "$1 doesn‘t exist." fi function check(){ if [ -e $1 ];then #函數體裡的參數 return 0 else return 1 fi } 2、計算兩數之和 #!/bin/bash function add(){ local tmp=0 i=$1 j=$2 let "tmp=i+j" return $tmp } add $1 $2 echo "$?" 2、指定位置參數值 使用set內建命令給指令碼指定位置參數的值(又叫重設)。一旦使用set設定了傳入參數的值,指令碼將忽略運行時傳入的位置參數(實際上是被set 重設了位置參數的值) 例: #!/bin/bash set 1 2 3 4 count=1 for var in [email protected] do echo "Here \$$count is $var" let "count++" done 注意:輸入時不管有多少參數都重設為四個參數。 如: . ./function03.sh a b c d e f 結果: Here $1 is 1 Here $2 is 2 Here $3 is 3 Here $4 is 4 注意:有什麼意義? 3、移動位置參數 回顧: shift,在不加任何參數的情況下,這個命令可以將位置參數向左移動一位。 例: #!/bin/bash until [ $# -eq 0 ] do echo "Now \$1 is:$1,total paramert is:$#" shift done 注意:活用位置參數, [email protected]/$*:所有參數 $1..$n:第n個參數,當n大於10時,要將n用()括起來 $0:指令碼本身 當用‘.’執行指令碼時為bash 當用bash執行指令碼時返回的檔案名稱 當用./scriptname執行時返回./scriptname $#:所有參數 擴充 指定左移的位元,shift n 例: #!/bin/bash echo "$0" until [ $# -eq 0 ] do echo "Now \$1 is:$1,total paramert is:$#" shift 2 done 注意:如果輸入命令時指定了奇數個參數,則指令碼會陷入死迴圈。 4、函數庫 為了和普通函數區別,在實踐中,建議庫函數使用底線(_)開頭 載入庫函數: 1、使用"點"(.)命令 2、使用source命令 例: 1、建立函數庫 實際上就是寫一個都是函數的指令檔 例:建立庫lib01.sh function _checkFileExist(){ if [ -e $1 ];then echo "File:$1 exists" else echo "File:$1 doesn‘t exists" fi } 2、使用 #!/bin/bash #source ./lib01.sh . ./lib01.sh _checkFileExist $1 系統函數庫: /etc/init.d/functions(我的系統是ubuntu,沒看到這個檔案) 一個27個函數
shell學習筆記之八(函數)