Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why `ls` list multiple files per line, but `ls pipe/redirect` list just 1 file per line? [closed]

Tags:

linux

bash

shell

Just curious, this is normal-expected behavior of ls:

user@host:~$ ls
Codes    Documents  Music   Pictures  Templates
Desktop  Downloads  Papers  Public    Videos

But when I use ls with pipe/redirection, it behave like ls -1:

user@host:~$ ls | cat
Codes
Desktop
Documents
Downloads
Music
Papers
Pictures
Public
Templates
Videos

Why? (and how to write such program that gives difference output between stdout and pipe like this?)


P.S. I also set alias l='ls -F', and this time pipe/redirection is no longer ls -1 style:

user@host:~$ l | cat
Codes/    Documents/  Music/   Pictures/  Templates/
Desktop/  Downloads/  Papers/  Public/    Videos/

Without using the alias, it does the command in ls -1 style, however:

$ ls -F | cat
Codes/
Desktop/
Documents/
Downloads/
Music/
Papers/
Pictures/
Public/
Templates/
Videos/
like image 549
neizod Avatar asked May 24 '14 20:05

neizod


People also ask

Which flags for the ls command would you use to list all files in long listing format?

The -lh flag is the same long list format command as above, however, the file size is displayed in a human-readable format. Notice the difference between the file size outputs in the previous two screens. This option, like the standard ls command, lists all non-hidden files and directories.

How do I list filenames only in Linux?

How to make ls display only filenames and file sizes in output. If you want the ls command output to only contain file/directory names and their respective sizes, then you can do that using the -h option in combination with -l/-s command line option.

Which command is used to list one line?

To show all entries for files, including those that begin with a dot (.), use the ls -a command. You can format the output in the following ways: List one entry per line, using the -l flag. List entries in multiple columns, by specifying either the -C or -x flag.

Which option is used with ls to list all the files?

Type the ls -l command to list the contents of the directory in a table format with columns including: content permissions. number of links to the content.


2 Answers

You can check this line from the source:

if (format == long_format)
  format = (isatty (STDOUT_FILENO) ? many_per_line : one_per_line);

It uses the isatty function to check if stdout points to a tty, and to print many_per_line if it does or one_per_line if it does not.

like image 111
Piotr Praszmo Avatar answered Oct 14 '22 03:10

Piotr Praszmo


Here is how GNU ls does it (ls.c):

  if (isatty (STDOUT_FILENO))
    {
      format = many_per_line;
    }
  else
    {
      format = one_per_line;
    }
like image 28
NPE Avatar answered Oct 14 '22 02:10

NPE