Ubuntu – How to evaluate grep result in bash

bashgrep

I want to grep a specific status of a service (tomcat8.service).

Only if the string was found, I want to execute some logic.

Problem: even if I execute the script on service name that does not exist ("asd" in this example), the if $status still matches and prints out. But why?

status = $(systemctl status asd.service | grep 'active')
echo $status

if $status
then 
    echo "$SERVICE was active"
    exit 0
fi 
exit 0

Result output is: asd.service was active, which is certainly not true.

The echo $status prints: status: Unknown job: =

Best Answer

You can make use of grep's return status.

systemctl status asd.service | grep 'active' \
    && status=active \
    || status=not_active

if [ "$status" == "active" ]; then
    [...]
fi

or even easier:

test $(systemctl status asd.service | grep 'active') \
    && echo "$SERVICE was active"

or if you prefer if:

if $(systemctl status asd.service | grep 'active'); then
    echo "$SERVICE was active"
fi

Anyways, take care about the keywords inactive, not active, active (exited) or alike. This will also match your grep statement. See the comments. Thanks @ Terrance for the hint.


Update:

No need for grep. systemctl has the command is-active included.

systemctl -q is-active asd.service \
    && echo "$SERVICE was active"

or:

if systemctl -q is-active asd.service; then
    echo "is active";
fi
Related Question