Shell Script – How to Introduce Timeout for Shell Scripting

shell-scripttimeout

I want to run a shell script that got a loop in it and it can go for ever which I do not want to happen. So I need to introduce a timeout for the whole script.

How can I introduce a timeout for the whole shell script under SuSE?

Best Answer

If GNU timeout is not available you can use expect (Mac OS X, BSD, ... do not usually have GNU tools and utilities by default).

################################################################################
# Executes command with a timeout
# Params:
#   $1 timeout in seconds
#   $2 command
# Returns 1 if timed out 0 otherwise
timeout() {

    time=$1

    # start the command in a subshell to avoid problem with pipes
    # (spawn accepts one command)
    command="/bin/sh -c \"$2\""

    expect -c "set echo \"-noecho\"; set timeout $time; spawn -noecho $command; expect timeout { exit 1 } eof { exit 0 }"    

    if [ $? = 1 ] ; then
        echo "Timeout after ${time} seconds"
    fi

}

Edit Example:

timeout 10 "ls ${HOME}"
Related Question