1

I am using ps to list all of the processes running on the machine I am connected to, searching them for my own processes, and then printing the number of processes I am running, like so:

ps -Af | grep '^mkuhlman' | wc -l

Problem is, checking against the actual list of processes, I'm only running 8, but wc is listing 9 processes. What am I doing wrong?

To clarify, I am not looking for matches to processes, but matches to my own username.

codeforester
  • 39,467
  • 16
  • 112
  • 140
Maggie K
  • 31
  • 8
  • 2
    `ps .. | grep '^[m]kuhlman' | wc -l` although the "wrong" way (which you'll see every day) is `ps .. | grep ... | grep -v grep | wc -l` . Good luck. – shellter Sep 05 '17 at 03:55
  • 1
    Possible duplicate of [Finding process count in Linux via command line](https://stackoverflow.com/questions/3058137/finding-process-count-in-linux-via-command-line) – codeforester Sep 05 '17 at 04:07

2 Answers2

0

Your pipeline has a few processes, and you're counting them.

Running ps is fine, but you might be happier with pgrep. It has a man page. (And ps -A seems at odds with grepping for your own username.)

J_H
  • 17,926
  • 4
  • 24
  • 44
  • Unfortunately, my teacher wants us to use these specific commands. I've looked through all our notes and the man pages for each, and I can't seem to figure out how to fix it. – Maggie K Sep 05 '17 at 04:01
  • Consider doing `ps -Af > /tmp/proc`. Then you don't need to worry about grep < proc or grep -v ps or wc or whatever processing pipeline showing up in the result. – J_H Sep 05 '17 at 04:21
0

Though grep -v grep would work in most cases, it can result in wrong output as it excludes all grep processes, not just the ones related to the ps command line. So, you could do this instead:

ps -Af | grep -E '^mkuhlman|__unique__' | grep -v __unique__

where __unique__ is a unique string that is unlikely to be used in the command line of other user processes.


See also:

codeforester
  • 39,467
  • 16
  • 112
  • 140