Reputation: 33
Normally the output of wc -l
command gives the number of lines in a file.
But, when we pipe the output of ls
command to it, it seems to show the number of files and directories and links in the current working directory correctly.
My question is that the output of the ls
command displays names of some files and directory in the same line. So, why in this case using ls | wc -l
gives the same output, as compared to ls -l | wc -l
.
Thanks in advance.
Upvotes: 3
Views: 2702
Reputation: 11804
A program can check whether a file descriptor refers to a terminal or not and present different outputs depending on this.
Check out isatty(3)
which can be used for this purpose.
In fact it is common practice to simplify the output when it is piped to make further processing easier for other programs it might be piped into. Especially the non-printable characters like terminal control codes which change colors, etc. could be a pain to process and are usually unnecessary when a user does not directly see the output.
Upvotes: 4
Reputation: 41503
ls
detects that it's being piped to another program instead of to the console, and outputs one file/directory per line. You can try ls | cat
to see this behavior.
Upvotes: 6