4

If I do git status --short, git lists files that are not tracked with two red question marks in front:

enter image description here

I'm trying to store this in a variable and print it with color later. Here's my bash script:

#!/bin/bash
status=$(git status --short)
echo -e "$status"

I thought the -e flag would cause bash to color the output, but it isn't working:

enter image description here

How can I do this?

Edit: the possible duplicate is asking how escape characters, specifically ANSI color control sequences, work. I think I understand how they work. My question is how to preserve those in the script output.

3

1 Answer 1

7

Most programs that produce color will, by default, only produce it when the output is to a terminal, not a pipe or file. Generally, this is a good thing. Often, however, there is an override switch. For example, for ls, one can use --color=always and, as a result, color can be saved in shell variables. For example:

enter image description here

grep also supports the --colors=always option.

For git, the corresponding option is its color.ui configuration setting:

git -c color.ui=always status
9
  • git status doesn't have a --color option. Is there any way to trick it into keeping the colors? Commented May 12, 2015 at 3:02
  • 1
    @Koveras For git, it seems that you have to change the defaults. I found some documentation here. See the part that mentions "You can also set it to always to ignore the difference between terminals and pipes."
    – John1024
    Commented May 12, 2015 at 3:04
  • 1
    @Koveras Also see unix.stackexchange.com/a/44283/53604
    – John1024
    Commented May 12, 2015 at 3:06
  • That works - can you include that in your answer? Commented May 12, 2015 at 3:08
  • 2
    Or just run git -c color.ui=always log.
    – lcd047
    Commented May 12, 2015 at 6:26

You must log in to answer this question.

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