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:


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

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

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:

       timeout - run a command with a time limit

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

   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'
    echo $cmd_output
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download