2016-03-08 27 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