1

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
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
user63019
  • 33
  • 3

1 Answers1

2

$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.

Tamás
  • 47,239
  • 12
  • 105
  • 124
  • Hmm, I've modified the command, but it still just prints the word "commentValue" instead of the contents. echo $check | nawk -F";" -v now=$now -v "commentValue=$commentValue" '{ printf( "[%u]=ACKNOWLEDGE_SVC_PROBLEM;"$1";"$2";2;1;0;admin;commentValue\n", now)}' >> $nagiosCommand – user63019 Aug 19 '11 at 21:36
  • It should be: ``echo $check | nawk -F";" -v now=$now -v "commentValue=$commentValue" '{ printf( "[%u]=ACKNOWLEDGE_SVC_PROBLEM;"$1";"$2";2;1;0;admin;%s\n", now, commentValue)}' >> $nagiosCommand``. Please read the documentation of ``printf`` in the ``awk`` manual. – Tamás Aug 19 '11 at 22:48
  • Ahhhh, duh. I had done that previously, but lef the trailing " at the very end. Thank you! – user63019 Aug 19 '11 at 23:26