How to automatically close netcat connection after data is sent?

Both other answers -c and -q given are correct in the right context, but it may help to summarize why there are multiple answers and give a more general solution.

These different options do the same thing but are different implementations of netcat:

  • -c GNU implementation of netcat
  • -q OpenBSD implementation of netcat.
  • -w (other?) OpenBSD implementation of netcat.

Some versions require an int to specify the number of seconds to wait before quitting for the -q and -w options. This int must be > 0 or >= 0, depending on the version.

If you are implementing something across multiple machines and are not sure they use the same implementation of netcat, you might consider wrapping your netcat call with the timeout program to kill netcat after a few seconds.

timeout 5 echo '{"hostUp": true}' | netcat localhost 8001

This approach is a bit clumsy because it puts an upper limit on the execution of netcat regardless of whether or not if it is sending data successfully, but if you are sending a small amount of data and have a few seconds to spare then this should work with any netcat implementation.


You can use -q parameter, but it will cause the netcat server to be closed also.

$ echo '{"hostUp": true}' | sudo /usr/local/bin/netcat -q 5 localhost 8001