Ubuntu: Sending an alert email if time for a curl command exceeds 1 sec


I am trying to a write one liner for sending an alert email if the time taken for curl command exceeds 1 sec.

if time curl {URI} > 1; then mailx -r me@domain.tld -s ALERT; fi  

How since time command returns more than just a numeric value, this fails.

Any ideas on how I can achieve this?


I'd save the PID of the curl process, sleep a second and just test whether it's still running with kill:

curl … &  pid=$!  sleep 1  if kill -0 $pid &>/dev/null; then    mailx -r me@domain.tld -s ALERT  fi  

You can test this easily with sleep 1 or sleep 2 respectively:

$ sleep 1 & pid=$!; sleep 1; if kill -0 $pid &>/dev/null; then echo running; fi  [1] 27520  [1]+  Done                    sleep 1  $ sleep 2 & pid=$!; sleep 1; if kill -0 $pid &>/dev/null; then echo running; fi  [1] 27599  running  


From the look of it, the result of curl does not seem to matter.

So I propose to kill the command if it spans more than one second by using timeout. Here is the one-liner:

timeout 1s curl {URI} || mailx -r me@domain.tld -s ALERT  

If it timeouts, it returns an error and the mailx command is run.

No tested but that should work.


Curl has an option for this, --max-time (and --connect-time, if you want to control time spend in the connect phase on the session). If timeout occurs, curl will return error-code 28.

So something like this:

curl --max-time 60 <URL>  if [ $? -eq 28 ]  then     mailx -r me@domain.tld -s ALERT  fi  

should do it.

I found this site Everything Curl which describes the capabilities of Curl.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »