Linux – How to capture the exit status of `nc` when run from `timeout`

linuxnetcatubuntu-14.04

I want to test connectivity to an arbitrary host using netcat. It seems the -w argument does not actually close the connection after 5 seconds. (This is on Ubuntu 14.04 and netcat-traditional 1.10-40). It will only continue to try connecting for 5 seconds. What I really want to know is if nc was able to succesfully connect to the host (exit status of 0).

To work around the nc issue, I've run nc thorugh the timeout command. This produces the desired functionality however timeout always exits with a 124 status code.

What I really want is the exit status of nc. How can I get that when running
timeout 5 nc -w 5 bach; echo $?

Best Answer

From the timeout man page (GNU coreutils 8.22) ...

--preserve-status
exit with the same status as COMMAND, even when the command times out

So your command would become

timeout --preserve-status 5 nc -w 5 bach; echo $?

However, I've just noticed that the original nc command uses the -w option which isn't what we want here. That tells nc to close the connection if it is idle not to give up if the connection takes too long.

The option we really want is -G which sets the TCP connection timeout. We want -w as well so that the connection will be closed (because we're not sending anything).

This gives a simple nc command of

nc -G 5 -w 5 bach; echo $?

Alternative approach is to just echo an empty line into nc to send to the server

echo | nc -G 5 bach; echo $?