Connect via Netcat and Send Messages in Bash Script [Duplicate]

When I am writing a bash script like the following:

#!/bin/bash

nc localhost [pseudoport]
echo "test"

it connects to the server but does not send the text "test".

It works with

#!/bin/bash

echo "test" | nc localhost [pseudoport]

The problem here is that the connection exits after something has been received.

How can I send multiple messages, in my case a fixed preamble followed by a variable data?

5

I have found a way to do this here: Send Commands to socket using netcat

You have to put the messages you want to send in a textfile (lets say msg.txt) and then

nc localhost [pseudoport] < msg.txt

The text file should look like this:

message1
message2
message3
...

Every message has to be in a new line.

The link I posted has a better explanation why this has to be done the way it is done here (there is no explanation in the duplicate article).

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest