I have to write a maintenance script that iterates over our IPs testing their connectivity to certain services such as nc -sip# mailin-01.mx.aol.com 25.

It has a flag -w ... but it's not what I think it is. That is, I only want this program to run for at max 3 seconds and the places we are connecting to are always up (unless major network problems that the script shouldn't worry about --- not its particular job and would be noticed before the script is run).

I just need it to connect and see if we are getting an error message. This is required before we assign an IP to a user for their web page (this is an alternative to CPanel stuff -- we want our own).

  • 2
    Why wouldn't you just store the IPs you have assigned out as you assign them? This is very unreliable and will not scale well. You are writing a web hosting control panel and this is the part you are stuck on? – jordanm Oct 20 '13 at 3:36
  • I'm not writing the panel, I'm writing some utilities. What does your comment about storing have anything to do with the answer? – Arian Oct 20 '13 at 4:07

The simplest way of doing this is with the timeout command. The timeout command lets you run a specified command, and if that command doesn't exit own it's own within a certain timeout, timeout kills it.

For example

# timeout 3 sleep 1; echo exit=$? 

# timeout 3 sleep 5; echo exit=$?

# timeout 3 nc google.com 80; echo exit=$?
nc: using stream socket

timeout is not defined in the POSIX standard, so it's not guaranteed to be everywhere, but it seems to be prevalent.



this worked



echo "Executing: ${cmd} for $seconds seconds"

sleep $seconds

if [ -d /proc/$cmdpid ]
echo "terminating program PID:$cmdpid"
kill $cmdpid
  • This is brilliant but I'm wondering if it is necessary ... there are other commands that can do the same and time out on their own – Mike Q May 12 '18 at 17:41

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