Bash Run command for certain time?

12

9

I am making bash script for my use. How can i run a command for certain time, like 20 second 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

Umair Riaz

Posted 2013-05-08T10:34:53.427

Reputation: 121

Answers

14

Hm, that should do the trick:

xmessage "Hello World" &
pidsave=$!
sleep 10; kill $pidsave

xmessage provides a quick test case here (in your case the airodump command should go there); & puts it into background.

$! holds the PID of the last started process (see e.g. https://stackoverflow.com/a/1822042/2037712); the PID gets saved into the variable pidsave.

After some waiting (sleep), send a TERM signal to the process.

mpy

Posted 2013-05-08T10:34:53.427

Reputation: 20 866

Thanks buddy it works but Now I have 1 problem. I want to see output which is created by command but xmessage windows doesn't show anything. – Umair Riaz – 2013-05-08T17:51:12.543

@UmairRiaz: xmessage was just an example. To adapt your example in the question and log the output of the command use some command > logfile & in the first line. Afterwards you can analyse logfile. – mpy – 2013-05-08T21:00:27.950

4

From the bash prompt you can use"

Hennes

Posted 2013-05-08T10:34:53.427

Reputation: 60 739

1

Another way is to use pgrep $pattern, or pkill $pattern; returns all the PIDs matching the given pattern, looking across all running processes on the machine. So to limit the scope of PIDs to only the ones you own, use: pgrep -P $mypid $pattern, or pkill -P$mypid $pattern

So to run a background process for a set length of time, your script would look something like this:

#!/bin/bash 
mypid=$$
run_something &
sleep $time_in_seconds
pkill -P $mypid something

Keep in mind that this will kill all processes with the same name pattern running under the current parent PID. So you could use this to start multiple processes, and kill them all simultaneously after a certain time.

Paul

Posted 2013-05-08T10:34:53.427

Reputation: 11