awk调用shell函数

 

[work@ shell_test]$ more conf_func_test.sh
#!/bin/sh

 

function method_add
{
        if [ $# -le 0 ]
        then
                return 1;
        fi

        fn_param=($@)
        fn_errmsg=""
        for((i=2;i<${fn_param[0]};i++))
        do
                fn_errmsg="${fn_errmsg}[${fn_param[${i}]}]"
        done

        if [ $# -le ${fn_param[0]} ]
        then
                echo "${fn_errmsg} param number error! ($# -le ${fn_param[0]})" >> "${fn_param[1]}"
                return 1
        fi

        local fn_res=0
        for((i=${fn_param[0]};i<$#;i++))
        do
                fn_res=`expr ${fn_res} + ${fn_param[${i}]}`
                if [ $? != 0 ]
                then
                        echo "${fn_errmsg} 'expr ${fn_res} + ${fn_param[${i}]}' error!" >> "${fn_param[1]}"
                        return 1
                fi
        done
        fn_res=`expr ${fn_res} / \( $# - ${fn_param[0]} \)`
        echo $fn_res
        return 0
}


export -f method_add


[work@ shell_test]$ more awk_shell_func_test.sh
#!/bin/sh

source ./conf_func_test.sh

shell_name=$0
log_file="$0.log"
func_str="method_add"

value=`method_add 5 "${log_file}" "${shell_name}" "--" "--"  1  2     3                     4`
echo $value

awk '
BEGIN{
        FS=OFS="\t";
}
{
        str="'${func_str}'";
        N=split(str,array,",");
        for(i=1;i<=N;i++)
        {
                a=0;
                cmd=array[i]" 5 '${log_file}'\t'${shell_name}'\t"FILENAME"\t"FNR"\t"$0;
                print cmd
                cmd | getline a;
                print a;
        }
}
END{

}' "test_file"

[[email protected] shell_test]$ more test_file
1       2       3       4       5
6       7       8       9       10
11 12 13 14 15


[[email protected] shell_test]$

 

有几点需要注意:

1、shell函数返回值为1-255,所以不能将算法结果当做返回值传递;

2、shell函数的计算结果,包括expr和(())的结果,都必须是整数,如果想得到小数结果,那么需使用bc;

你可能感兴趣的:(shell)