How to run a process with a timeout in Bash?

LinuxShellTimeout

Linux Problem Overview


> Possible Duplicate:
> Bash script that kills a child process after a given timeout

Is there a way to write a shell script that would execute a certain command for 15 seconds, then kill the command?

I have tried sleep, wait and ping but maybe I am using them wrong.

Linux Solutions


Solution 1 - Linux

Use the timeout command:

timeout 15s command

Note: on some systems you need to install coreutils, on others it's missing or has different command line arguments. See an alternate solution posted by @ArjunShankar . Based on it you can encapsulate that boiler-plate code and create your own portable timeout script or small C app that does the same thing.

Solution 2 - Linux

Some machines don't have timeout installed/available. In that case, you could background the process; its PID then gets stored as $!; then sleep for the required amount of time, then kill it:

some_command arg1 arg2 &
TASK_PID=$!
sleep 15
kill $TASK_PID

At this URL I find that there are mentioned, more than one solutions to make this happen.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlanFView Question on Stackoverflow
Solution 1 - LinuxKaroly HorvathView Answer on Stackoverflow
Solution 2 - LinuxArjunShankarView Answer on Stackoverflow