Read full message in a while loop in bash

妖精的绣舞 提交于 2019-12-24 21:53:28

问题


I connect to a server by /dev/tcp to receive incoming xml messages. The script below is running well, but if there is an blank character in the xml message, the message is abrupt. But I need the to read full message. Can I solve this by integrate the closing xml-tag in the while-loop?

#!/bin/bash
exec 3<>/dev/tcp/192.168.24.23/1234

processResponse() {
  RESPONSE=$1 
  if [[${RESPONSE:0:10} == "<firsttag>" ]]; then
    curl -X POST --data "postdata=$RESPONSE" http://localhost/index.php
  fi 
}

while read response
    do processResponse $response
done <&3

The xml-message will be like:

<firsttag>
   <secondtag>message with blanks inside</secondtag>
</firsttag>

回答1:


As chepner said, your approach isn't really suitable, but if you must forgo an XML parser, you can solve this for cases like the shown one. Rather than scripting a while loop, I'd use awk to read and assemble the message lines.

awk '/<firsttag>/   { RESPONSE = "" }
     /<firsttag>/,/<\/firsttag>/    { RESPONSE = RESPONSE$0 }
     /<\/firsttag>/ { system("curl -X POST --data \"postdata="RESPONSE"\" http://localhost/index.php") }
    ' <&3


来源:https://stackoverflow.com/questions/47636710/read-full-message-in-a-while-loop-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!