I strongly suggest you rather use the is-active query from systemctl
systemctl is-active gravity
which returns the current service status, or:
sytemctl --quiet is-active gravity
which just exits with 0 if active and non-zero otherwise, which means you could use
if sytemctl --quiet is-active gravity; then
echo " >> Gravity service is running ..."
else
echo " >> Gravity service not running ..."
fi
From the manual:
is-active PATTERN…
Check whether any of the specified units are active (i.e. running). Returns an exit code 0 if at least one is active, or non-zero otherwise. Unless --quiet is specified, this will also print the current unit state to standard output.
Now for the issue itself:
Green color is passed as part of the string and thus the match fails. Compare it to this:
if [ "$(echo 1 | grep --color=yes 1)" = 1 ]
then echo equal
else echo different
fi
#different
if [ "$(echo 1 | grep --color=no 1)" = 1 ]
then echo equal
else echo different
fi
#equal
See how it is different in the first case and identical in the second one because [ stra == strb ] tests for exactly matching strings.
You could make a regex match to avoid this problem via
if [[ $(echo 1 | grep --color=yes 1) =~ 1 ]]
then echo equal
else echo different
fi
#equal
but be aware that the regex MIGHT match the color coding (not in the case of words like "active", though). Note how this needs the extended test [[ ]] from bash.
Some programs are smart enough to not forward the color to a pipe, e.g. grep, but one may force it:
echo 1 | grep 1 | cat -A
1$
echo 1 | grep 1 --color=yes | cat -A
^[[01;31m^[[K1^[[m^[[K$
So this is how the colorizing of 1 in bold red looks like. More on bash colors here.
[is a command,]is its last argument. The command does not change the way the arguments are parsed (for comparison: it's different with[[which is a shell keyword). This means in general you should double-quote. You got away this time, still good practice is a virtue and it's way easier always to quote than to wonder each time if it's safe not to quote. – Kamil Maciorowski Jan 13 '22 at 21:27