shell 函數 awk函數總結
author:潤明 2012-2-16 QQ:226399587 http://blog.csdn.net/runming918
shell 函數、awk函數、以及awk調用shell中的函數,下面統一總結一下。昨晚寫腳本函數,然後就把函數在shell中的各種使用方法都實驗了一篇,下面直接貼代碼吧。
1、 普通shell函數:
#!/bin/sh function fun_test4() { _message=$1 if [ "$_message" -ge "0" ];then return 0 elif [ "$_message" -lt "0" ];then return 1 fi } if fun_test4 -10 then echo "shell call the function : 10 greater than 0 " else echo "shell call the function : less than 0" fi |
幾點說明:
1.1、向函數傳遞參數:
向函數傳遞參數就像在一般腳本中使用特殊變量$ 1 , $ 2 . . . $ 9一樣,函數取得所傳參數後,將原始參數傳回s h e l l腳本,因此最好先在函數內重新設置變量保存所傳的參數。這樣如果函數有一點錯誤,就可以通過已經本地化的變量名迅速加以跟蹤。函數裏調用參數(變量)的轉換以下劃線開始,後加變量名,如: _ F I L E N A M E或_ f i l e n a m e。
1.2、 返回值:
函數中可以用return命令返回,如果return後面跟一個數字則表示函數的Exit Status;返回0表示真返回1表示假。
1.3、獲取函數返回值--再貼一個例子:
#!/bin/sh function fun_test3() { if [ $# -eq 1 ];then _message="$1" else echo "Parameter error:" exit fi
if [ "$_message" -ge "0" ];then returnVal="ok" elif [ "$_message" -le "0" ];then returnVal="no" else returnVal="0" fi echo $returnVal } value1=`fun_test3 1` value2=`fun_test3 -2` value3=`fun_test3 0` echo "shell call the function : " $value1 echo "shell call the function : " $value2 echo "shell call the function : " $value3 |
2、 Awk函數:
2.1、無參數函數:
#!/bin/sh awk ' #注意函數括號裏面需要打兩個空格 function fun_test1( ) { print "hello world! " } BEGIN{ FS="|" } { printf "in awk no Parameter:" $2 " " #注意調用函數值得帶()括號 fun_test1() }' sourcedata/pcscard.dat |
2.2、帶參數函數:
#!/bin/sh awk ' function fun_test2(message) { if(message>0){ returnVal="ok" } else if(message<0){ returnVal="no" } else{ returnVal="0" } return returnVal } BEGIN{ FS="|" #注意這裏函數的參數是放在括號內的,和shell中的函數就不同了。 print "in awk have Parameter:" fun_test2(1) print "in awk have Parameter:" fun_test2(-2) print "in awk have Parameter:" fun_test2(q) } {}' sourcedata/pcscard.dat |
3、 Awk中調用shell中的函數:
#!/bin/sh function fun_test4() { _message=$1 if [ "$_message" -ge "0" ];then return 0 elif [ "$_message" -lt "0" ];then return 1 fi }
export -f fun_test4
awk ' BEGIN{ FS="|" printf "awk call shell function: " _value=system("fun_test4 10") print _value if(_value == "0") { print "shell call the function : 10 greater than 0" } else { print "shell call the function : less than 0" } } {}' sourcedata/pcscard.dat exit |
注意:awk中如果需要調用shell函數需要將函數export爲系統參數,然後調用的時候用system;個人感覺還是直接用awk自己定義函數方便。