Umair Riaz
Umair Riaz

Reputation: 559

Bash Run command for certain time?

I am making a bash script for my use. How can I run a command for certain time, like 20 seconds and terminate command? I tried a lot of solutions but nothing works, I also tried timeout command with no success. Please give me some solution for this.

For example: I want to run this command in script and terminal after 10 sec

some command

Upvotes: 55

Views: 70831

Answers (5)

Vladimir Myagdeev
Vladimir Myagdeev

Reputation: 71

Use sleep and && operand:

sleep [time in seconds] && your-command

Example:

sleep 7 && echo 'Hello world!'

Upvotes: -8

mato
mato

Reputation: 643

On systems that do not provide timeout command, you can use the following:

your-cmd & sleep 30 ; kill $!

That will run potentially long running your-cmd with timeout of 30 seconds.

If your-cmd does not finish within 30 seconds, it will be sent TERM signal.

Upvotes: 30

keypress
keypress

Reputation: 799

I suggest 2 options:

  • On systems where you have the timeout command, you can use it according to man timeout.
  • On systems without it (e.g. CentOS 5), you can use the script supplied with bash /usr/share/doc/bash-3.2/scripts/timeout. Use it according to its usage information.

Upvotes: 2

Robert Gomez
Robert Gomez

Reputation: 1349

Here are some bash scripts and a program called timelimit which may solve your problem. Kill process after it's been allowed to run for some time

EDIT: I think I found a better solution. Try using the timeout program. From the man page: "timeout - run a command with a time limit". For example:

timeout 5s sleep 10s

It basically runs your command and after the specified duration it will kill it.

Upvotes: 99

Matthew Graves
Matthew Graves

Reputation: 3294

Are you looking to schedule the execution of the script? Then cron is your friend.

Upvotes: -1

Related Questions