Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ls give different output when piped

Tags:

bash

Printing to terminal directly:

$ ls
a.out  avg.c  avg.h

Piping to cat

$ ls | cat
a.out
avg.c
avg.h

Why does ls give a different output based on destination?

like image 341
kev Avatar asked Dec 21 '11 02:12

kev


3 Answers

ls can actually determine if it's outputting to a terminal or a file (with the isatty library call). If it detects a console, it will try to make it more compact for easier viewing.

like image 167
Chris Eberle Avatar answered Oct 15 '22 22:10

Chris Eberle


ls automatically behaves like ls -1 when piped.

This is usually what you want when you are piping ls to awk or something like that, since it will treat the output of ls on a line-by-line basis.

To override this default behavior, you can use ls -C | cat.

like image 29
Dennis Avatar answered Oct 15 '22 22:10

Dennis


So that each line is one entry only, allowing the command the output is piped to to work as would likely be expected. For example (given your ls output), the following would probably not be what you want:

$ ls | sort -r
a.out  avg.c  avg.h

But because sort didn't know there was more than one item per line, it couldn't do anything. Compare this to what actually occurs:

$ ls | sort -r
avg.h
avg.c
a.out

You can achieve the (unexpected) first behavior by passing -C to ls.

like image 1
Andrew Marshall Avatar answered Oct 15 '22 23:10

Andrew Marshall