How I can count how many suspended proceses there are in a shell script linux bash

Viewed 145

I tried to write a shell script that shows and counts how many suspended processes there are.

But I succeeded only to show the suspended processes with:

#!/bin/bash
list_ps=`ps aux | awk '$8~/T/'`
echo "$list_ps"

I tried to count the suspended processes with:

nr=0
for i in $list_ps
do
  nr=`expr $nr + 1`
done

Of course this didn't work because it counted every word there was even with the first row that had the USER PID STAT COMMAND.

Can you give me any suggestion on how I should do it? Also here is the output for "ps aux | awk '$8~/T/" after I stopped some sleep processes.

USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
alexsan+  6441  0.0  0.0   9008   736 pts/0    T    16:17   0:00 sleep 5000
alexsan+  6511  0.0  0.0   9008   820 pts/0    T    16:18   0:00 sleep 5000
alexsan+  7041  0.0  0.0   9008   760 pts/0    T    16:21   0:00 sleep 333
3 Answers

additional characters can be added to the state field (depending on the options you use), so this might be a safer approach:

ps aux | awk '$8~/T/'

to count how many processes you have with a header :

ps aux | awk '$8~/T/' | wc -l

to skip the header :

count=$(ps aux | awk '$8~/T/' | wc -l)
echo $((count -1))

one line version :

echo $(( $(ps aux | awk '$8~/T/' | wc -l)-1))

within single awk :

ps aux | awk 'NR>1 && $8~/T/' | wc -l

Using the option --no-header of the ps command, you will not need to substract 1 from the number of lines of output you get from wc -l, so you just have to issue:

ps --no-header aux | awk '$8 ~ /T/' | wc -l

And since the header will contain the 'T' of 'STAT' in field #8, it was necessary to filter this line out.

Within single awk could you please try following.

echo $(( $(ps aux | awk '$8~/T/{count++} END{print count-1}')))

Or to assign to a variable simply:

var=$(ps aux | awk '$8~/T/{count++} END{print count-1}')
Related