Bash – How to store colored text in a variable and print it with color later

bashcolorsescape-charactersgitshell-script

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.

Best Answer

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