Capturing color output into 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 with:

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

The above script keeps a new line unchanged (thanks to Capturing multiple lines in a Bash variable ), but removes color from the output.

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

+6
source share
3 answers

The problem is not that bash removes color output before saving text, but git refuses to produce color output in the first place, probably because it can say that its STDOUT is not a terminal. Many teams do this (e.g. ls ). Most of them have an option telling them to use color in any case for use in this particular situation (for example, --color for ls ). Consult your git documentation if it has such an override option.

+8
source

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

Remember that command output captured this way does not necessarily include a trailing newline, so you want to add that if you plan to print it later.

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

For a more general solution that works with other programs that do not provide color redefinition, the best way to do this is with a script, as shown in Can the color output be captured via shell redirection?

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

+1
source

As Kilian Fot said:

"Consult your git documentation if it has such an override option."

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

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

Using git version 1.9.2, I try "git status --color" and "git - color state", but none of them seem to have this flag. Maybe not yet implemented?

However, capturing ls color output works with this:

 IFS="" output=$(ls -l --color) echo -e "$output" 
+1
source

Source: https://habr.com/ru/post/893574/


All Articles