在老外的论坛上看到的:http://www.unix.com/shell-programming-scripting/49026-external-function-awk.html
Hi.
Here is a script that attempts various methods of calling functions:
<!-- ntstart-->#!/usr/bin/env sh
# @(#) s1 Demonstrate functions with awk.
# ____
# /
# | Infrastructure BEGIN
set -o nounset
echo
debug=":"
debug="echo"
## The shebang using "env" line is designed for portability. For
# higher security, use:
#
# #!/bin/sh -
## Use local command version for the commands in this demonstration.
echo "(Versions displayed with local utility \"version\")"
version >/dev/null 2>&1 && version bash awk
my_shell_local()
{
echo " Local function $FUNCNAME called."
}
kamel_seg()
{
echo " Function $FUNCNAME called with arguments \"$*\"."
}
echo
echo " Function is exported to sub-shells:"
export -f kamel_seg
typeset -F
# | Infrastructure END
# \
# ---
echo
echo " Calling shell function from shell:"
kamel_seg hello
echo
echo " Calling shell function from awk:"
awk '
BEGIN { print " In awk" ; kamel_seg }
'
echo
echo " Calling shell function from awk system() call:"
awk '
BEGIN { print "In awk - system" ;
system(" echo Hi from system call" ) ; system( "kamel_seg from awk" ) }
'
echo
echo " Calling awk function:"
awk '
function my_function( message )
{
print " awk function my_function called, argument:" message
}
BEGIN { print " Calling my_function from BEGIN block."
my_function( " Hello there." )
}
'
echo
echo " Calling awk program that calls a shell script with system():"
awk '
BEGIN { print " Calling helper." ; system( "./helper" ) }
'
exit 0<!-- ntend-->
<!-- width:820px; height:1282px;-->
Producing:
<!-- ntstart-->% ./s1 (Versions displayed with local utility "version") GNU bash 2.05b.0 GNU Awk 3.1.4 Function is exported to sub-shells: declare -fx kamel_seg declare -f my_shell_local Calling shell function from shell: Function kamel_seg called with arguments "hello". Calling shell function from awk: In awk Calling shell function from awk system() call: In awk - system Hi from system call Function kamel_seg called with arguments "from awk". Calling awk function: Calling my_function from BEGIN block. awk function my_function called, argument: Hello there. Calling awk program that calls a shell script with system(): Calling helper. Script "helper" called. awk script called from shell script helper<!-- ntend-->
<!-- width:820px; height:482px;-->
Among the other points, this illustrates that shell functions can be called from awk system(), provided the shell functions are exported (frankly, I was not expecting this; I simply was trying to exhaust all the possibilities).
The brief declare output shows the difference between local and exported functions.
Best wishes ... cheers, drl
Shell与Awk函数互调
本文演示了Shell脚本中函数与Awk脚本中函数互相调用的方法,包括如何从Awk调用Shell函数及通过system()从Awk执行Shell命令。此外,还展示了如何使Shell函数在子Shell中可用。
2942

被折叠的 条评论
为什么被折叠?



