I have this simple line writing JSON to a TCP server

echo "{\"some\":\"json-data\"}" > /dev/tcp/localhost/9091 > cat

I would have thought that some connection would be created, and the data would get piped to the terminal/tty, but this doesn't work, the line is just skipped over, and the bash script completes right away.

I also tried:

echo "{\"some\":\"json-data\"}" > /dev/tcp/localhost/9091 | tail -f

On my TCP server, I get a connection, but the pipe is quickly broken.

How can I write a bash command that will stream the data from the TCP server to the bash script?

  • 2
    This sort of thing is usually done with nc or netcat or socat – thrig Jul 11 '17 at 19:08
  • yeah I am going to resort to that soon. Any idea why the above wouldn't work? – Alexander Mills Jul 11 '17 at 19:09
  • if you can demonstrate the equivalent command with netcat, that keeps piping data to cat or tail, that would get my vote. – Alexander Mills Jul 11 '17 at 19:10
  • @thrig you might be interested in the answer provided – Alexander Mills Jul 11 '17 at 19:20
  • nope. ls: /dev/tcp: No such file or directory – thrig Jul 11 '17 at 19:40

Open a persistent FD. This is very awkward in bash... people tend to end up allocating the file numbers by hand.

exec 3<>/dev/tcp/localhost/9091
echo "{\"some\":\"json-data\"}" >&3
cat <&3

the above assumes the socket is closed after the reply is sent.

  • thanks, I saw something similar from Diego here, stackoverflow.com/questions/4739196/… – Alexander Mills Jul 11 '17 at 19:12
  • sorry, what do you mean by "people tend to end up allocating the file numbers by hand." – Alexander Mills Jul 11 '17 at 19:12
  • @AlexanderMills Like I just did with the number 3. – sourcejedi Jul 11 '17 at 19:13
  • oh, should I pick a file descriptor other than 3? I guess 0,1,2 are stdin, stdout, stderr right? – Alexander Mills Jul 11 '17 at 19:14
  • 1
    @AlexanderMills More information about this technique here – sourcejedi Jul 11 '17 at 19:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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