问题
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