16

I want to capture the color output from git status in a variable and print it later.

So far I have come up to:

status=$(git status -s)
echo -e "$status"

The above script keeps the newline intact (thx to Capturing multiple line output into a Bash variable) but strips the color from the output.

Is there a way to keep the color in the variable and echo it?

Community
  • 1
  • 1
Kostas
  • 8,356
  • 11
  • 47
  • 63

3 Answers3

13

The problem is not that bash strips the color output before storing the text, but that git refuses to produce the colored output int he first place, probably because it can tell that its STDOUT is not a terminal. Many commands do this (e.g. ls). Most of these have an option telling them to use color anyway, for use in precisely this situation (e.g. --color for ls). Consult your git documentation whether it also has such an override option.

Kilian Foth
  • 13,904
  • 5
  • 39
  • 57
6

For a git-specific solution, you can force git to provide color via the color.status configuration option. To override the configuration entry for this single command, use git -c color.status=always status.

Remember that command output captured this way doesn't necessarily include the trailing newline so you'll want to add that if you plan on printing it later.

out=$(git -c color.status=always status)
printf "$out\n"

For a more generic solution that works with other programs that don't provide color overrides, a better way to do it is with script as shown at Can colorized output be captured via shell redirect?

In those cases, you would want to use status=$(script -q /dev/null git status | cat)

Community
  • 1
  • 1
vmrob
  • 2,966
  • 29
  • 40
3

As Kilian Foth mentioned:

"Consult your git documentation whether it also has such an override option"

Git documentation says (http://git-scm.com/book/en/Customizing-Git-Git-Configuration#Colors-in-Git):

"if you want color codes in your redirected output, you can instead pass a --color flag to the Git command to force it to use color codes"

Using git version 1.9.2, I am trying "git status --color" and "git --color status" but none of them seem to have that flag valid. May be is not yet implemented?

However, capturing the colored output of ls works with this:

IFS=""
output=$(ls -l --color)
echo -e "$output"
minterior
  • 381
  • 3
  • 6