Reputation: 984
My goal is to grep for a count of processes older than 'x' minutes in bash.
So far, I can grep for all the process execution times:
ps -eo etime,cmd | grep mysuperspecialprocess.sh | grep -Ev 'grep' | awk '{print $1}'
I pipe a wc -l
to get a count at the end.
How can I grep or loop through the result to restrict it to processes older than a certain number of minutes?
Upvotes: 2
Views: 1475
Reputation: 2868
Give this tested version a try.
It searches a specified running process, and count all occurences which has an associated elapsed time greater than a specified number of seconds.
Set parameters' values first and run it.
$ cat ./script.sh
#!/bin/bash --
process_name=mysuperspecialprocess.sh
elapsed_time_seconds=600
ps -eo etimes,cmd | fgrep "${process_name}" | fgrep -v fgrep | ( count=0 ; while read etimes cmd ; do \
if [ $etimes -gt $elapsed_time_seconds ] ;\
then \
count=$((count+1)) ;\
fi ;\
done ; echo $count )
etimes instructs ps to display seconds.
Upvotes: 2
Reputation: 67507
awk
to the rescue!
starting with the etime field you can do something similar to this, ignores seconds.
$ awk 'NR>1{n=split($1,a,":"); # split the field
if(n==2) mins=a[1]+0; # if hours not present set mins
else {d=split(a[1],h,"-"); # check for days
hours=(d==2?h[1]*24+h[2]:h[1]); # incorporate days in hours
mins=hours*60+a[2]} # compute mins
print $1, mins}' etimes
00:04 0
02:30:44 150
01:03:11 63
1-01:01:01 1501
3-00:02:00 4322
Upvotes: 0