1

To output all lines into a file /tmp/ps.txt

$ ps -e >/tmp/ps.txt    

To count it with wc -l

$ wc -l /tmp/ps.txt
172

To count it without exporting a file.

$ ps -e | wc -l
173

Why ps -e | wc -l get one more line?

I don't think ctrl-d has the right explanation for my question.

$ echo "test" | wc -l
1

Please try it in your terminal, it would yield 2 as ctrl-d would say.

  • You are counting 1 for the one line that you are echoing to wc. That's a different situation than with ps. – ctrl-d Jan 10 '17 at 2:55
  • Your commands are counting the number of processes running on the machine at the time the ps was run. Since in the first case, where you use a file, the wc is run separately, so not in the ps. When you run it as a pipe the wc is running at the same time and so it is another process in the ps output, thus the count. You could see the difference by adding a tee to the pipeline (which will increase the number by one more, of course) whichn will produce a file you can look at and see the ps, wc and tee processes. – MAP Jan 10 '17 at 3:29
3

ctrl-d's answer is correct.

You appear not to have understood what the ps command is for. It lists processes on your system.

When you run the ps command, that running instance itself is a process.

When you run the wc command, that is also a process.

If you stick some cat commands in the pipeline, each of those is also a process and each will cause ps to output one more line of information:

[vagrant@localhost ~]$ ps | wc -l
4
[vagrant@localhost ~]$ ps | cat | wc -l
5
[vagrant@localhost ~]$ ps | cat | cat | wc -l
6
[vagrant@localhost ~]$ ps | wc -l
4
[vagrant@localhost ~]$ ps
  PID TTY          TIME CMD
22912 pts/0    00:00:00 bash
29651 pts/0    00:00:00 ps
[vagrant@localhost ~]$ 

The fact that echo "test" | wc -l displays "1" is entirely irrelevant.

11

The extra line is the wc program that is running. It is executed at the same time as ps, not after that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.