Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Shell 函数 awk函数总结

shell 函数、awk函数、以及awk调用shell中的函数,下面统一总结一下。昨晚写脚本函数,然后就把函数在shell中的各种使用方法都实验了一篇,下面直接贴代码吧。1、 普通shell函数:
#!/bin/shfunction fun_test4(){         _message=$1         if [ "$_message" -ge "0" ];then              return 0       elif [ "$_message" -lt "0" ];then              return 1       fi}if fun_test4 -10 thenecho "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/shfunction 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 : " $value1echo "shell call the function : " $value2echo "shell call the function : " $value3
 2、 Awk函数:2.1、无参数函数:
#!/bin/shawk "#注意函数括号里面需要打两个空格function fun_test1(  ){       print "hello world! " } BEGIN{ FS="|"   }{  printf "in awk no Parameter:" $2 " "  #注意调用函数值得带()括号  fun_test1()}" sourcedata/pcscard.dat     
2.2、带参数函数:
#!/bin/shawk " 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/shfunction 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自己定义函数方便。