I am a beginner with bash/shell scripting and I am trying to handle a specific output that comes from systemctl when a specific service is not found. For example, when I run systemctl status xyz
the output that returns is Unit xyz could not be found.
If the service is not found I want to update a variable to hold a string ServiceName="xyz service not found"
. If the service is found, I don't want to update the variable at all and keep it the same.
This is a part of an effort of trying to find if a specific service is running or not, and store the output from the variable in a csv file that gets shipped to s3 and then I can query the bucket via aws Athena. (I have this implemented already, just providing additional information).
so far I have tried
#!/usr/bin/env bash
serviceName=$(systemctl status xyz | head -n 1 | cut -c 3-)
if [[ $serviceName$(systemctl status xyz | grep 'could not be found') ]]; then
serviceName="xyz not found"
else
serviceName=$(systemctl status xyz | head -n 1 | cut -c 3-)
fi
Which returns from running bash test.sh (the name of the file containing the provided code).
Unit xyz could not be found.
Unit xyz could not be found.
Unit xyz could not be found.
I am running this with other commands, so I would prefer not to exit the entire script on failure.
Thank you in advance.