2

This question already has an answer here:

I am working on displaying output like ls command (just ls, no options). And I have a working program using the system calls. But I experienced a strange behavior while testing as shown below.

$ ls 
a b c
$ ls > somefile
$ cat somefile
a
b
c

so, as you see the output is written one file per file, NO ADDITIONAL SWITCHES WERE GIVEN TO LS. You can test it out. So from above I infer, ls command has some built-in logic to display it one per line if written to a file via redirection.

To add to the puzzle, I believe it's the shell that interprets the redirection.

So I am confused I would like to kown what exactly is making the output one per line if redirected to a file? Any hint?

marked as duplicate by Gilles, roaima, eyoung100, cuonglm, G-Man Sep 3 '15 at 4:12

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
  • In both ls invocations, the output is redirected to a file. In the first case, a device file, in the second case, presumably a regular file, in anycase not a terminal device file, as otherwise you'd see a b c as well. – Stéphane Chazelas Sep 2 '15 at 16:02
3

Usually by testing if a relevant filehandle is attached to a tty:

% perl -le 'print -t STDOUT ? "yes" : "no"'
yes
% perl -le 'print -t STDOUT ? "yes" : "no"' > out
% < out
no
% 

Or via C, something like:

#include <sys/ioctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

...

int foo;
if (ioctl(STDIN_FILENO, FIONREAD, &foo) == -1) {
    printf("yes\n");
} else {
    printf("no\n");
}
  • 1
    Specifically, it uses the isatty C library call, which calls the fstat system call. – Tom Hunt Sep 2 '15 at 15:55
  • 2
    Or just [ -t 1 ]. – Stéphane Chazelas Sep 2 '15 at 16:03
  • @StéphaneChazelas Please elaborate about [ -t 1 ]. – Tulains Córdova Oct 5 '15 at 19:56

Not the answer you're looking for? Browse other questions tagged or ask your own question.