Sinan
Sinan

Reputation: 103

I am getting syntax errors when trying to use a system call within awk

I am getting crazy because of syntax errors or incorrect usage of awk in combination with a system call. I have read several pages regarding it, but still I cannot get it working. See my code.

The current error is:

awk: cmd. line:1: /sent/ { system("echo \"mail has been sent\"")} !/sent/ { system("curl -k -i -u username:password -X POST -H "Content-Type: application/json" -d '{"source": "client-01", "name": "smtp-bounce-check", "output": "Cannot send e-mail, e-mail bounced", "status": 2}' https://monitoring:4567/results")}
awk: cmd. line:1:                                                                                                                                                    ^ syntax error

I tried escaping, using single quotes, double quotes, but still cannot get it working.

#!/bin/bash

gen_data1='{"source": "client-1", "name": "smtp-bounce-check", "output": "Cannot send e-mail, e-mail bounced", "status": 2}'

tail -f /var/log/maillog| grep --line-buffered "relay=some-host.name.com"|grep --line-buffered "status="| awk '/sent/ { system("echo \"mail has been sent\"")} !/sent/ { system("curl -k -i -u username:password -X POST -H "Content-Type: application/json" -d '"'${gen_data1}'"' https://monitoring:4567/results")}'

Upvotes: 0

Views: 35

Answers (1)

KamilCuk
KamilCuk

Reputation: 140960

You need to escape it more.

gen_data1='{"source": "client-1", "name": "smtp-bounce-check", "output": "Cannot send e-mail, e-mail bounced", "status": 2}';
gen_data1_escaped=$(<<<"$gen_data1" sed 's/"/\\\\\\"/g')
awk '
   /sent/{ 
       system("echo \"mail has been sent\"")
   }
   !/sent/{ 
       system("curl -k -i -u username:password -X POST -H \"Content-Type: application/json\" -d \"'"${gen_data1_escaped}"'\" https://monitoring:4567/results")
   }
'
  • you need to double-escape all " that are inside gen_data1. Ie. transform each " into \\\". It will be first un-escaped by awk, then by shell inside system() call.
  • the quotes around "Content-Type: application/json" need to be escaped too
  • the quotes around ${gen_data1} need to be there and need to be double quotes. From what I've found single quotes do not work inside system() call inside awk, ie. test awk "{ system('echo hello world') }"

Upvotes: 2

Related Questions