1

If I run a command in a subshell, I can collect the stdout into a variable, such as:

var=$(echo 'hello world')
echo $var

Will print 'hello world' as expected.

If I add colour and a new line, this too is ok:

var=$(echo "Text in \n\e[34mBlue")
echo -e $var

Prints "Text in Blue" with the word 'Blue' coloured and on the next line as expected.

However if I try this with git output, such as

var=$(git status)
echo $var

It loses all the newlines and colouring.

How can I capture the output of a git command and print it later on, while preserving formatting and colouring in bash?

2

The default value of git's color.ui configuration is auto, which only uses colours when output is to a TTY. You can change that in your configuration to always to have the output be coloured regardless.

Most usefully for your use case, there is a -c option to git that allows overriding a configuration value just for the current command. You can use that to set color.ui to always:

var=$(git -c color.ui=always status)
printf '%s\n' "$var"

Note though that in your second example

var=$(echo "Text in \n\e[34mBlue")
echo -e $var

it's actually the echo -e line that causes the colours to appear - the escape codes weren't interpreted by the echo inside the command substitution, and the backslashes and other characters were literally there. It wasn't that the colour codes were stored that time and forgotten when they came from git - they were created at the end in one case, and never at all in the other.

| improve this answer | |
0

Try this:

var=$(git status)
echo "$var"

This is about bash quoting mechanism, without "" quoting around $var, newline inside is treated as token separator just as blank space. See bash manual for more info

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.