7 ms·
> What a reasonable default is depends on the type of application and how it's likely to be used. No default (other than calling isatty) is reasonable, because
by rollcat 4y ago
> What a reasonable default is depends on the type of application and how it's likely to be used.
No default (other than calling isatty) is reasonable, because you don't know (and you don't want to know) what your output is being piped through.
If you really must, add a flag to force enable/disable escape codes.
> "prog | grep foo" outputs to the terminal. From prog's perspective it doesn't, but it does. Do you want escape sequences in there? Sometimes you do, sometimes you don't.
What happens if "prog" outputs an escape sequence (e.g. set color) on one line, and outputs another one (reset color) a few lines down? grep might match one or the other, or none, or something in the middle. grep might want to output its own escape sequences (like it can do for highlighting a match). "prog" can't know what grep could possibly want to output, without inspecting grep's entire argument line, and effectively re-implementing all of grep - bug-for-bug, compensating for differences in GNU, BSD, BusyBox, etc.
There is no sane way to handle every edge case here, and you will get frustrated every time you hit one.
> Even "prog | less" outputs to the terminal, indirectly, and less can interpret escape sequences.
$ echo hello | less > hello.txt
$ cat hello.txt
hello
It can, but should it?
http://harmful.cat-v.org/cat-v/ http://harmful.cat-v.org/cat-v/
- arp242 4y ago> No default (other than calling isatty) is reasonable, because you don't know (and you don't want to know) what your output is being piped through. Exactly because you don't know it makes sense to optimize for the common case. > What happens if "prog" outputs an escape sequence (e.g. set color) on one line, and outputs another one (reset color) a few lines down? Don't do that then. Or do use isatty() is your escape sequences are complex like that. > It can, but should it? Yes, because it's useful.
- rollcat 4y ago> Exactly because you don't know it makes sense to optimize for the common case. What is "common"? What if I want grep to match text that has an escape code in the middle of it - do I have to first inspect the generated escape codes? What if I'm redirecting the output to a file, and opening that file in a program that doesn't process escape codes? Every sane tool I know of calls isatty. It's only those that don't that cause problems. > Yes, because it's useful. Please read the article I've linked about "cat -v". There's no doubt someone (perhaps many people) find it useful; that doesn't mean it isn't a bad idea and/or a poor design.