4

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?

2 Answers 2

6

I got here by Google and didn't quite find the answer I was looking for: you can invoke ag as

ag --color --group

to force it to use the default colors and group results by file, regardless of whether the output is a tty.

Here's what it looks like in action.

2

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.

1
  • awesome, wish I give bonus points for the source code citation! Commented Sep 28, 2014 at 22:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .