Why does wc get wrong result with output from ps

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

To count it without exporting a file.

$ ps -e | wc -l

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

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

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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

Solution 2

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:

[[email protected] ~]$ ps | wc -l
[[email protected] ~]$ ps | cat | wc -l
[[email protected] ~]$ ps | cat | cat | wc -l
[[email protected] ~]$ ps | wc -l
[[email protected] ~]$ ps
  PID TTY          TIME CMD
22912 pts/0    00:00:00 bash
29651 pts/0    00:00:00 ps
[[email protected] ~]$ 

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

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply