2016-03-08 22 views
1

我的目标是grep计算在bash中超过'x'分钟的进程数。运行超过x分钟的进程的grep计数

到目前为止,我可以grep对所有的流程执行时间:

ps -eo etime,cmd | grep mysuperspecialprocess.sh | grep -Ev 'grep' | awk '{print $1}'

我管一个wc -l末获得计数。

我该如何对结果进行grep或循环以将其限制为超过特定分钟数的进程?

回答

2

给这个测试版本一个尝试。

它搜索指定的正在运行的进程,并计算所有相关经过时间大于指定秒数的出现次数。

首先设置参数值并运行它。

$ 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指示PS显示秒。

+0

** shellcheck **报告的主要问题**已修复。 –

0

awk来救援!

从etime字段开始,你可以做类似的事情,忽略秒。

$ 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