Ag output appears different in the terminal vs when piped to a file

io-redirectionterminal

When I run the ag command to search text files, I get output that looks like this on the command line (full results not shown):

❯ ag dependency
140317155505.md
27:The Bundler dependencies API ...

140423193022_python_packages.md
61:`distutils` is part of the Python standard ....

There are newlines in the output. However, when I pipe or redirect to a file, I get output like this:

140317155505.md:27:The Bundler dependencies API...
140423193022_python_packages.md:61:`distutils` is part of the Python standard...

Here there is an extra colon instead of a newline. How does this work? I would think that ag just writes to STDOUT and is unaware of the actual target of STDOUT– am I wrong in thinking that it does not have access to this information?

Best Answer

The program ag (I'm not familiar with it), could use the system call

stdout_is_tty = isatty(1);

The isatty() function tests whether fd is an open file descriptor referring to a terminal.

This allows it to modify the output depending on where it is writing to.

I also think I found the relevant source code section

/* If we're not outputting to a terminal. change output to:
* turn off colors
* print filenames on every line
*/
if (!isatty(fileno(stdout))) {
  opts.color = 0;
  group = 0;
....

See also man isatty.

Related Question