Reputation: 5
I have a fairly large bash function library that I use in an application. The library gets imported as an environment file. Since the functions are exported, I can use these functions in other bash scripts without any issues.
However I have another issue where I need to use an awk scriptlet and I want to be able to use a couple of functions from the bash library if possible.
So in short I want to be able to do one of the two things:
Works:
[root@test@Test1001 scripts]# . mfg.env
[root@test@Test1001 scripts]# set -o posix;OSMAJVER=12 EVMAJVER=11 EVMINVER=1 SYSTEM_ARCH=SSA HOST=test;check_flag RAD
[root@test@Test1001 scripts]# echo $?
0
Doesn't work:
[root@test@Test1001 scripts]# . mfg.env
[root@test@Test1001 scripts]# awk -v st=ssa -v 'env=OSMAJVER=12 EVMAJVER=11 EVMINVER=1 SYSTEM_ARCH=SSA HOST=test' -f /tmp/s1.awk /tmp/template.mf
bash: check_flag: No such file or directory 127
s1.awk
BEGIN {
FS=":"
if (system("set -o posix;"env)!=0) {
print "***ERROR - ENV string not valid to shell - cannot continue"
exit 1
}
}
/^[[:space:]]*#/{next}
/^[[:space:]]*$/{next}
{
# field 3 processing
n_a=split($3,a_st,",")
# field 4 re-glue around ":" if required
cmd=$4
for (i=5; i<=NF; i++) cmd=cmd":"$i
if (cmd) cmd="set -o posix;"env";"cmd
f=0;for (i=1; i<=n_a && !f; i++) if (a_st[i]==st) f=1
print "CMD: "cmd
if ($3=="" || $3=="*" || f)
system(cmd)
}
mf file:
text:S3:rcs,ssa:check_flag RAD
I want to be able to process the above line only if the "check_flag RAD" returns true.
Upvotes: 0
Views: 419
Reputation: 295687
No, you cannot.
You can use export -f
to export the function from your parent shell, and then run another instance of bash from awk as a child process. However, this is near the very height of hackery; given more details on what you actually intend to accomplish, we could almost certainly find a better-practice approach.
A better-practice approach is to structure your awk script to write a stream which your shell-native code can read from and operate over -- see BashFAQ #1 for best-practices around reading from an input stream field-by-field.
Upvotes: 4