I want to write a command that listens to some port (say port 22222), receives a single line of text, and splits that line by spaces into port, host, and text by spaces. The text can have spaces in it too. So, for example, 1234 localhost blah de blah would be be split into 1234 for the port, localhost for the host, and blah de blah for the text. If the port is 0, the program exits. Otherwise the program sends the value of text to the host at the port and loops back to listening.
So I have in the terminal:
nc -k -l localhost 22222|some code goes here I think
and
echo 2016 localhost blah blah|nc localhost 22222
will cause blah blah to be sent to localhost at port 2016 and
echo 0 localhost blah blah|nc localhost 22222
will cause the program to exit
My question is what exactly goes into the “some code goes here I think” section?
Advertisement
Answer
Upon receive nc
will echo the data to stdout, so you can process it as follows:
nc -k -l localhost 22222 | while read line do # "$line" contains the received text, do whatever you need with it ... done