23

The output of ls (with no arguments) appears to separate filenames with linebreaks.

Evidence:

  • ls | grep foo works as expected, with grep treating each filename as a separate line of input.

  • ls > files.txt; vim files.txt --> in Vim, each file is on a separate line

And yet in the terminal the output of ls puts multiple files on one line, separating the filenames with spaces to make nicely aligned columns:

$ ls
a.txt  b.txt  c.txt

So my question is, how does ls do this?

Is it using some special control char to 'fake' a newline? Or does it know when its output is being piped to another command, and format its output differently in this case?

2 Answers 2

26

Or does it know when its output is being piped to another command, and format its output differently in this case?

Yes. From the full manual (available through info ls if the documentation is installed):

If standard output is a terminal, the output is in columns (sorted vertically) and control characters are output as question marks; otherwise, the output is listed one per line and control characters are output as-is.

If you like the one column output, you can run

ls -1

to get it in the terminal as well.

2
  • 8
    Specifically, the function ls uses to determine whether or not the output is a terminal is isatty(3).
    – Blrfl
    May 14, 2012 at 14:37
  • Also somewhat related, if one wants to test this in a simple shell script one can run tty -s and check its return status. May 14, 2012 at 16:39
11

ls detects it when you pipe its output. You can see it in the documentation:

If standard output is a terminal, the output is in columns (sorted vertically) and control characters are output as question marks; otherwise, the output is listed one per line and control characters are output as-is.

If you want each file in the output to be placed on a separate line regardless of the pipe redirection, you can use

ls -1

You must log in to answer this question.

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