Harish Ganesan Harish Ganesan - 2 years ago 89
Linux Question

Pipelining of cat and ls commands

I am a newbie to linux . I have been learning about cat command when i tried this .

[email protected]:~$ cat file
[email protected]:~$ cat file | ls -l

The command displays the content of the current folder instead of the folder mentioned in the file .. But when i did this

[email protected]:~$ cat file
[email protected]:~$ ls -l $(cat file)

The contents of the expected folder displays correctly . Why cant i not use the pipeline in this case ?

Answer Source

In the first example you are passing the output of cat file to the input of ls -l. Since ls -l does not take any input, it does not do anything regarding the output of cat file. However in the second example you are using $(cat file) which puts the output of cat file in the place of an argument passed to ls -l, and this time ls -l has the text inside file in the right place for doing something with it. The issue here is noticing the difference between the standard input of a program and the arguments of a program. Standard input is what you have when you call scanf in C, for example; and the arguments are what you get in the argv pointer passed as parameter to the main procedure.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download