1

I'm trying to get the original color of the output of this command with grep:

sudo systemctl status telegraf | grep -e ● -e Active

Output of command

with this command the output is red, but i want it to match the original color, which is in this case green when the service is active and red or no color when its inactive.

I tried as described here: https://unix.stackexchange.com/questions/75527/how-can-i-keep-color-codes-with-grep-input, but this does seem to work only with ls command.

sudo systemctl status telegraf --color=always | grep --color=never -e ● -e Active

This throws an error: systemctl: unrecognized option '--color=always'

This of course has no color at all: sudo systemctl status telegraf | grep --color=never -e ● -e Active

It would be great if someone knew what I could do to achieve the original color output.

Thanks in advance.

1 Answers1

1

When you observe red, it comes from grep. You can (and did) turn this off with grep --color=never …. Neither this red nor --color=never of grep overrides some green generated by systemctl. The point is there is no green when systemctl prints to a pipe; this is the main issue here.

If you managed to make systemctl print green to a pipe, then your grep --color=never … would not alter the color.

There is a way. I took it from this answer to a somewhat similar question.

sudo SYSTEMD_COLORS=1 systemctl status telegraf | grep --color=never -e ● -e Active

The other question does not involve sudo. In your case sudo may interfere. It may or may not allow you to set a variable (or the variable) in the above way. It may or may not allow you to pass it this other way:

SYSTEMD_COLORS=1 sudo -E systemctl status telegraf | grep --color=never -e ● -e Active

See man 8 sudo and man 5 sudoers where they mention the environment. It may be your sudo is configured to sanitize the environment no matter what; in such case try this:

sudo sh -c 'SYSTEMD_COLORS=1 systemctl status telegraf' | grep --color=never -e ● -e Active

Do you really need sudo to invoke systemctl status …? Maybe you can simply do this without sudo:

SYSTEMD_COLORS=1 systemctl status telegraf | grep --color=never -e ● -e Active