Question

consider the following... when I execute 'ls' without any flags, it returns the results in a single line, like the following:

me@myComp /cygdrive/c/test/
$ ls
folder1/  folder2/  folder3/

now, if I want to grep the results for something, say '2', I get the following:

me@myComp /cygdrive/c/test/
$ ls | grep 2
folder2/

Shouldn't it return the entire line? I would expect this result has I used ls -l | grep 2.

It seems to me that either the pipe operator is changing the input to grep in some way, or that somehow ls is aware of the pipe and changes its own output.

folder1/ folder2/ folder3/ is a single string, is it not? so how then does grep know to only return folder2/, and not folder1/ folder2/ folder3/?

Was it helpful?

Solution

See the manpage for ls, namely the flag -1:

-1 (The numeric digit ``one''.) Force output to be one entry per line. This is the default when output is not to a terminal.

If you want to force multi-column output use

-C Force multi-column output; this is the default when output is to a terminal.

So to answer your question, yes, ls is aware where the output goes and it has well-defined behavior depending on it which you can easily override.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top