Search code examples
bashvariablesnawk

Pass variable to nawk in bash?


I'm trying to pass a variable to nawk in a bash script, but it's not actually printing the $commentValue variable's contents. Everything works great, except the last part of the printf statement. Thanks!

echo -n "Service Name: "

read serviceName

echo -n "Comment: "

read commentValue

for check in $(grep "CURRENT SERVICE STATE"  $nagiosLog |grep -w "$serviceName" | nawk -F": " '{print $2}' |sort -u ) ; do
    echo $check | nawk -F";" -v now=$now '{ printf( "[%u]=ACKNOWLEDGE_SVC_PROBLEM;"$1";"$2";2;1;0;admin;$commentValue"\n", now)}' >> $nagiosCommand

done

Solution

  • $commentValue is inside an invocation to nawk, so it is considered as a variable in nawk, not a variable in bash. Since you do not have such a variable in nawk, you won't get anything there. You should first pass the variable "inside" nawk using the -v switch just like you did for the now variable; i.e.:

    ... | nawk -F";" -v now=$now -v "commentValue=$commentValue"
    

    Note the quotes - they are required in case $commentValue contains whitespace.