Skip to content
Advertisement

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

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

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement