2

Consider the following command:

ls
dir1 dir2 file1
x1   x2   y2

when this output is piped into e.g. grep each file/directory is processed as an 'item'.

ls | grep f
file1

So obviously there is a distinction between the actual output that a ls produces and the input that is processed by grep.

Since grep operates on lines one could expect that ls | grep f would show the whole first line, namely: dir1 dir2 file1

What am I missing here? What is the mechanism behind this behavior?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
  • 2
    It's all in the (ls) manual... The default format shall be to list one entry per line to standard output; the exceptions are to terminals or when one of the -C, -m, or -x options is specified. – don_crissti Jul 11 '16 at 12:29

2 Answers2

4

It's possible for a command to detect when its output is going to a TTY or not. Thus in this particular case, when ls detects that its output is not going to a TTY, it behaves as if -1 were passed as an argument.

You can see this, and that grep is not doing anything special by using cat:

ls | cat
phemmer
  • 71,831
  • alright, this makes sense. Does anybody know how e.g. a bash script could create an output switch for the cases two (tty and stdout)? Would be interesting to see this. – Anton Harald Jul 11 '16 at 12:34
  • Not sure what you mean. But if you're asking how to detect whether output is going to a TTY in a shell script, use if [ -t 1 ]; ... or if test -t 1; ... – phemmer Jul 11 '16 at 12:38
  • yes, this line was the thing I was looking for. – Anton Harald Jul 11 '16 at 18:44
1

To see how ls behaves when its output is being redirected, you can try running

ls | cat

or

ls -1

which is how ls behaves when its output doesn't go to a TTY.

choroba
  • 47,233