Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does timeout not work within a bash script?

I tried to kill a process if it exceeds more than a few seconds.

The following works just fine when I run it in the terminal.

timeout 2 sleep 5

But when I have a script -

#!/bin/bash
timeout 2 sleep 5

it says

timeout: command not found

Why so? What is the workaround?

--EDIT--

On executing type timeout, it says -

timeout is a shell function

like image 600
user657592 Avatar asked Mar 28 '14 13:03

user657592


People also ask

What is bash timeout?

The timeout command stops an executed process after the timeout period: $ timeout 1s bash -c 'for((;;)); do :; done' $ echo $? 124. Here, we run an endless loop. We set a timeout of one second before timeout should kill the process.

How do I delay in bash?

It is as easy as typing sleep N . This will pause your script for N seconds, with N being either a positive integer or a floating point number. Consider this basic example: echo "Hello there!" sleep 2 echo "Oops!

What is Shell timeout?

timeout is a command-line utility that runs a specified command and terminates it if it is still running after a given period of time. In other words, timeout allows you to run a command with a time limit.

How do I parse a csv file in shell script?

Parsing CSV File Into a Bash Array In this example, we read the line from our input CSV, and then appended it to the array arr_csv (+= is used to append the records to Bash array). Then we printed the records of the array using a for loop. This reads lines from input. csv into an array variable, array_csv.


1 Answers

It's seems your environment $PATH variable does not include /usr/bin/ path or may be timeout binary exists in somewhere else.

So just check path of timeout command using :

command -v timeout

and use absolute path in your script

Ex.

#!/bin/bash
/usr/bin/timeout 2 sleep 5

Update 1#

As per your update in question, it is function created in your shell. you can use absolute path in your script as mentioned in above example.

Update 2# timeout command added from coreutils version => 8.12.197-032bb, 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

}

Example:

timeout 10 "ls ${HOME}"

Source

like image 78
Rahul Patil Avatar answered Sep 23 '22 16:09

Rahul Patil