由于语法错误或与系统调用结合使用awk的不正确,我快疯了。我已经阅读了几页有关它的内容,但是仍然无法正常工作。查看我的代码。
当前错误是:
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
我尝试使用单引号,双引号进行转义,但仍然无法正常工作。
#!/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")}'
答案 0 :(得分:2)
您需要进一步逃脱。
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")
}
'
"
中的所有gen_data1
进行两次转义。就是将每个"
转换为\\\"
。它将首先由awk
进行转义,然后由system()
调用中的shell进行转义。"Content-Type: application/json"
周围的引号也必须转义${gen_data1}
周围的引号必须存在且必须为双引号。根据我的发现,在system()
内的awk
内不能使用单引号,即。测试awk "{ system('echo hello world') }"