ilikecats
ilikecats

Reputation: 319

How to split given text into 3 variables in bash and send to host at port?

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?

Upvotes: 1

Views: 283

Answers (2)

unconditional
unconditional

Reputation: 7666

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

Upvotes: 2

prushik
prushik

Reputation: 331

Since you are piping the output of netcat (nc) into "some code goes here I think", "some code goes here I think" needs to be a program or script that reads standard input and does what you want with that data. Using pipes on the command line aren't the only way or getting the output of netcat and doing something with it. Since you mentioned you are using bash, probably the simplest thing to do would be to take the output on nc and then store that in a variable, then you can use another program like cut or awk to split the string up:

raw=`nc -k -l localhost 22222`
part1=`echo $raw | cut -f 1`
part2=`echo $raw | cut -f 2`
part3=`echo $raw | cut -f 3-`

Which should get you the parts you want stored in bash environment variables, which you can do what you like with later (e.g., exit if $part1=0). Note that those are backticks in my example, not quotes. Backticks in bash take the result of the command inside them and return it as a string.

Upvotes: 1

Related Questions