bash

Aborting a script if any command takes too long to run


I have an application called A that receives an input n and runs for some time before returning the answer.

I would like to execute A for increasing sizes of n with the following simple bash script:

#!/bin/sh

time ./A 10
time ./A 20
time ./A 30
.
.
.

However I need something very important as well. If a time call takes too long to execute, because the input is large, then I need the entire bash script to stop running.

Is there an easy way of doing this?


Solution

  • The following could work:

    #! /bin/bash                                                                                   
    
    timeout 2 time sleep 1                                                                         
    if [[ $? == 124 ]]                                                                             
    then                                                                                           
        exit;                                                                                      
    fi                                                                                             
    
    timeout 2 time sleep 3                                                                         
    if [[ $? == 124 ]]                                                                             
    then                                                                                           
        exit;                                                                                      
    fi                                                                                             
    
    timeout 2 time sleep 5                                                                         
    if [[ $? == 124 ]]                                                                             
    then                                                                                           
        exit;                                                                                      
    fi                                                                                             
    

    On my system, that produces:

    0.00user 0.00system 0:01.00elapsed 0%CPU (0avgtext+0avgdata 1696maxresident)k
    0inputs+0outputs (0major+73minor)pagefaults 0swaps
    

    Not the prettiest output, but it stops after the first line: the results of timing sleep 3 and sleep 5 are never shown.

    Note that timeout is a GNU coreutils command, and not installed everywhere (if it can be installed at all on your system). The exit status may also differ: 124 is the default, but it is probably better to test for $? != 0.