Behram Mistree
Behram Mistree

Reputation: 4308

Preserve color codes when exec-ing

As part of a larger program, I'm making a call to grep, and outputting its results to standard out:

// execute grep command
cmd := exec.Command(GREP_BIN_PATH, argArray...)
stdout, err := cmd.StdoutPipe()
if err != nil {
    log.Fatal(err)
}
stderr, err := cmd.StderrPipe()
if err != nil {
    log.Fatal(err)
}

err = cmd.Start()
if err != nil {
    log.Fatal(err)
}
go io.Copy(os.Stdout, stdout)
go io.Copy(os.Stderr, stderr)
cmd.Wait()

If I make an identical call to grep directly from the terminal, grep outputs multi-color text (eg., highlighting in red any match in its output). Doing a little research, it seems as though there are special ansi color codes that grep/other programs use to change color highlighting.

Where do these colors go when I exec a command from go? Is there any way that I can exec from within go to preserve ansi color codes and just copy the output from grep to standard out (similar to the post here, but for go)?

(I also know that I could manually re-insert color codes. But that seems painful, and I'd rather just pipe grep's original colors.)

Please let me know if something in the question is unclear/needs clarification. Thanks!

Upvotes: 2

Views: 1416

Answers (1)

Etan Reisner
Etan Reisner

Reputation: 81012

grep and most other color-using tools detect whether they are sending output to a terminal or not when they decide whether to use color.

Files and pipes, etc. often don't want the color codes and don't know what to do with them.

You can force grep to output colors anyway with the --color=always flag though.

Upvotes: 8

Related Questions