Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 276
Umair Riaz Avatar asked May 08 '13 08:05

Umair Riaz


People also ask

How do I run a shell script at a specific time?

Using at. From the interactive shell, you can enter the command you want to run at that time. If you want to run multiple commands, press enter after each command and type the command on the new at> prompt. Once you're done entering commands, press Ctrl-D on an empty at> prompt to exit the interactive shell.

How do I run a Linux script in 5 seconds?

What you could do is write a shell script with an infinite loop that runs your task, and then sleeps for 5 seconds. That way your task would be run more or less every 5 seconds, depending on how long the task itself takes. You can create a my-task.sh file with the contents above and run it with sh my-task.sh .


2 Answers

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.

like image 200
Robert Gomez Avatar answered Oct 19 '22 08:10

Robert Gomez


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.

like image 40
mato Avatar answered Oct 19 '22 07:10

mato