Rich Rich -4 years ago 89
Linux Question

Linux bash: timeout a program if the program hangs in there and echo 'timeout'

I have a program which will print out either pass or fail. I want to detect the programs which hang in there and echo 'timeout'

I wrote a script like this:

#!/bin/bash

echo -n 'test' && timeout 5 ./mytest | grep -q -i 'passed' && echo ', passed'|| echo ', failed'

if [ $? -eq 124 ]; then
echo 'timeout'
fi


But it will treat the programs hang in there as 'failed' and kill the program. Any suggestions will be appreciated. Thanks!

Answer Source

man timeout:

NAME
       timeout - run a command with a time limit

SYNOPSIS
       timeout [OPTION] DURATION COMMAND [ARG]...
       timeout [OPTION]

DESCRIPTION
   Start COMMAND, and kill it if still running after DURATION.
...

Here's an example:

cmd_output=`timeout 5 ./mytest`

if [ $? -eq 124 ]; then
    echo 'timeout'
else
    echo $cmd_output
fi
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download