Consider the following command:

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

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?

  • 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. Jul 11, 2016 at 12:29

2 Answers 2


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
  • 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. Jul 11, 2016 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, 2016 at 12:38
  • yes, this line was the thing I was looking for. Jul 11, 2016 at 18:44

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

ls | cat


ls -1

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

  • There is more difference like for terminal output option -q is set by default
    – Philippos
    May 16, 2017 at 14:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .