PS Command – Why Does wc Get Wrong Result with Output?

pswc

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.

Best Answer

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.

Related Question