When I am writing a bash script like the following:


nc localhost [pseudoport]
echo "test"

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

It works with


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?

  • You are running the script in the command line correct? – Robby1212 Feb 10 '18 at 16:56
  • yes that is correct – OcK Feb 10 '18 at 16:57
  • 1
    What do you mean "send continuously"? Do you want to send a fixed preamble followed by variable data from a file or standard input through nc (or any process consuming its standard input stream for that matter)? – David Foerster Feb 10 '18 at 17:20
  • Yes @DavidFoerster I wanted to send a fixed preamble followed by a variable data. The link I posted describes how you should do it (from a file). – OcK Feb 10 '18 at 17:27
  • @DavidFoerster done. – OcK Feb 10 '18 at 18:37

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:


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).

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.