Anowarul Kabir
Anowarul Kabir

Reputation: 57

How to check infinite loop in bash?

I have been trying to run an executable using a bash multiple times. There is a chance that this executable will fall into infinite loop, or segfaults. I know there is no try-catch in bash but we can bypass that using:

{ #try
    "myCommand" && "do what i want"
} || { #except
    "handle error"
}

But this is not capable of understanding infinite loop. How can I handle this problem?

Upvotes: 0

Views: 516

Answers (2)

UtLox
UtLox

Reputation: 4164

You can user timeout from the gnu coreutils.

Here a example for a timeout of 10 seconds

timeout 10s yourscript.sh

Upvotes: 2

vintnes
vintnes

Reputation: 2030

Bash can't tell you what's going on inside myCommand unless that loop sends a signal or modifies the system/environment. You could run your #try in the background &, then do something if it's still running after a certain amount of time. $! refers to the last backgrounded task.

Check out Job Control in Bash.

myCommand && doWhatIWant &
sleep 10
ps $! &>/dev/null && kill $!

Upvotes: 0

Related Questions