15

I want to limit the time a grep process command is allowed to run or be alive.

For example. I want to perform the following:

grep -qsRw -m1 "parameter" /var

But before running the grep command I want to limit how long the grep process is to live, say no longer than 30 seconds.

How do I do this?

And if it can, how do I return or reset to have no time limit afterwards.

random
  • 15,201
yael
  • 549

4 Answers4

13

You can use timelimit, it is available in the default ubuntu or you could compile it yourself.

timelimit executes a command and terminates the spawned process after a given time with a given signal. A “warning” signal is sent first, then, after a timeout, a “kill” signal, similar to the way init(8) operates on shutdown.

feniix
  • 251
7

Here's some slightly hackish bash for that:

grep -qsRw -m1 "parameter" /var &

GREPPID=$!

( sleep 30; kill $GREPPID ) &

fg $GREPPID

Basically, it starts the search in the background, then starts a subshell that waits 30 seconds and then kills the search process. If the search takes <30s, the process will already be dead. It's not a great idea to kill a process that's already dead since there's a very small chance something else will reuse the pid, but for something like this it's generally okay. Lastly, the search is put back in the foreground and will run until it finishes or is killed.

4

Create a new file called "tgrep" and put in it the following (or call it whatever you want):

#!/bin/bash
grep $@ &
PID=$!
sleep 30 && kill $PID 2>/dev/null &
wait $PID
exit 0

Next, run chmod a+x tgrep. Now if you want to use it you can type

./tgrep -i "results" /home/dan/*txt

Or you can just use it as tgrep (without the ./ and be able to use it from any directory) if you place it in a directory contained in your $PATH variable (like /home/dan/bin/, if that is in your $PATH variable, otherwise you can add it).

Jarvin
  • 7,386
0

You can just use timeout:

timeout 30 "grep -qsRw -m1 "parameter" /var"