Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing colorized output to a bash variable

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?

like image 807
Kostas Avatar asked Jul 26 '11 09:07

Kostas


People also ask

How do you assign the output of a command to a variable in a shell script?

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...]


1 Answers

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.

like image 51
Kilian Foth Avatar answered Oct 30 '22 12:10

Kilian Foth