Vincent
Vincent

Reputation: 1604

Bash : If command timeout, execute something else

I am doing the following :

timeout 180 bash myscript.txt

myscript.txt is supposed to be fully executed in less than 180 seconds. IF NOT, I want emergencyscript.txt to be executed. Is it possible to do so ?

Like

timeout 180 [bash myscript.txt] [bash emergencyscript.txt]

Upvotes: 4

Views: 9274

Answers (3)

fflores
fflores

Reputation: 432

#!/bin/bash
if ! timeout 180s bash myscript.txt; then bash emergencyscript.txt; fi

Upvotes: 2

Dylan
Dylan

Reputation: 92

maybe try checking to see if timeout failed or not?

timeout 180 bash myscript.txt
if [ $? -ne 0 ]
then
#....do stuff....
fi

That's dependent on timeout or the script giving a non-zero exit value if it takes too long though.

Upvotes: 1

chepner
chepner

Reputation: 530940

The exit status of timeout is 124 if the command times out. You can test for this explicitly.

timeout 180 bash myscript.txt
exit_status=$?
if [[ $exit_status -eq 124 ]]; then
    bash emergencyscript.txt
fi

Any other value for exit_status is the result of myscript.txt running to completion.

Upvotes: 14

Related Questions