2

Look at the diffreent output of ls versus ls -1

$ ls
 filea1.txt   fileb.txt    listB1.xml   listC.xml
 filea.txt    listA1.xml   listB.xml   'name with spaces 2.txt'
 fileb1.txt   listA.xml    listC1.xml  'name with spaces.txt'

$ ls -1
filea1.txt
filea.txt
fileb1.txt
fileb.txt
listA1.xml
listA.xml
listB1.xml
listB.xml
listC1.xml
listC.xml
'name with spaces 2.txt'
'name with spaces.txt'

Which is quite OK for me. Thing go different if you redirect the output to file. I'd expect that file diffes, but they are identical.

$ ls -1>/tmp/ls-1.out
$ ls >/tmp/ls.out

$ cat /tmp/ls-1.out
filea1.txt
filea.txt
fileb1.txt
fileb.txt
listA1.xml
listA.xml
listB1.xml
listB.xml
listC1.xml
listC.xml
name with spaces 2.txt
name with spaces.txt

$ cat /tmp/ls.out
filea1.txt
filea.txt
fileb1.txt
fileb.txt
listA1.xml
listA.xml
listB1.xml
listB.xml
listC1.xml
listC.xml
name with spaces 2.txt
name with spaces.txt

Why is the latter just one-column output but not the multi-column as when there's no redirection to file?

Tagwint
  • 2,410
  • 1
  • 13
  • 22

1 Answers1

1

-1 is enabled by default when ls’s output is redirected.

Strictly speaking, the default output format is -1, as specified in POSIX:

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. If the output is to a terminal, the format is implementation-defined.

You can force columnar output to a file by explicitly specifying -C:

ls -C > /tmp/ls-C.out
Stephen Kitt
  • 411,918
  • 54
  • 1,065
  • 1,164
  • Thanks for the link, `. If the output is to a terminal, the format is implementation-defined.` <<< that's the point not really mentioned in man. – Tagwint Jul 25 '18 at 10:41
  • Man pages describe a specific implementation, so they don’t need to mention that — they can state exactly what the output is when it’s going to a terminal ;-). – Stephen Kitt Jul 25 '18 at 11:28
  • How does `ls` know if the output is a terminal? – Jaime Hablutzel Feb 22 '22 at 08:38
  • 1
    @Jaime it calls [`isatty`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/isatty.html) to check whether its standard output is a terminal. – Stephen Kitt Feb 22 '22 at 08:43