0

When running ls in terminal, output is variously colored:

ls console output

AFAIK this colorasing is accomplished by espace sequences (vt).

But running ls | hexdump -cC shows only characters and LFs. Redirection to file leads to similar results.

ls | hexdump -cC console output

How is that?

0

GNU ls only outputs escape sequences for colorized text when writing to a terminal, not when redirected to a file or pipe.

For that, use ls --color=always.

The GNU ls manual says:

   Using color to distinguish file types is disabled both by default and
   with --color=never.  With --color=auto, ls emits color codes only when
   standard output is connected to a terminal.  [...]

I'm guessing that your ls command behaves like ls --color=auto by default, possibly through the use of an ls alias.

  • Ok, the question should be more like "how do commands know whether stdout is terminal", but since it does not, this is the answer. – mcpiroman Jun 12 '19 at 19:26
  • @mcpiroman This is easy to test. In the shell, one could use if [ -t 1 ]; then ...; fi to test whether file descriptor 1 (standard output) is a terminal. – Kusalananda Jun 12 '19 at 19:51
  • Well that's interesting cause I thought the streams and pipes where designed to be transparent i.e. that the actual output file (linux file) is not known nor relevant. I'm guessing that's a little bit of a hack to that system, but that's ok. – mcpiroman Jun 12 '19 at 20:05
  • See superuser.com/a/932170. – egmont Jun 12 '19 at 20:45
  • @mcpiroman It is transparent, in the sense that writing to a pipe and writing to a file is done in exactly the same way. Likewise is reading done the same way. A pipe may however not be searched (you can't set the file pointer to a specific location in a data stream coming off a pipe). There are also ways to inspect the nature of file descriptors. A program may then decide to act on the result of such inspection, obviously. – Kusalananda Jun 12 '19 at 20:56

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