I'm creating a script in bash to perform the below use cases,
- Finding specific services based on specific words on their names
- Stopping these services in a specific order like: service_1, service_2 and so on
- Checking if these services are stopped and if there is a one that is still up & running, It will print out it's name
This is my progress, Firstly, I've found the services based on some words that only exists with their names as below,
service_1=$(ls /etc/systemd/system | grep -e text1 | awk -F ' ' '{print $1}')
service_2=$(ls /etc/systemd/system | grep -e text2 | awk -F ' ' '{print $1}')
service_3=$(ls /etc/systemd/system | grep -e text3 | awk -F ' ' '{print $1}')
Then, I've stopped them in the order I want as below:
if [ ! -z "$service_1" ] //if service exists
then
systemctl stop $service_1
else
:
fi
if [ ! -z "$service_2" ] //if service exists
then
systemctl stop $service_2
else
:
fi
if [ ! -z "$service_3" ] //if service exists
then
systemctl stop $service_3
else
:
fi
Here comes the problem. As you know, when stopping a service, it may take some time to be fully stopped so as per the conditions above it will move forward in stopping the second service without full stopping the previous one. What I want is stopping the services in order so before stopping the second service the first one should be fully stopped and so on. How to make that ? I think this can be made by loops but I am missing the way. Regarding the third use case, I've defined the below variables that holds the word "inactive" after filtering the status output of the services as an indicator that the services are stopped:
service_1_status=$(systemctl status $service_1 | grep -e "inactive")
service_2_status=$(systemctl status $service_2 | grep -e "inactive")
service_3_status=$(systemctl status $service_3 | grep -e "inactive")
Then, I've tried to loop on them to find out if there is a service that is still active to print it's name as below:
arr=($service_1_status $service_2_status $service_3_status $service_q_inf_status)
for i in "${arr[@]}"
do
if "${arr[$i}" != "inactive"
then
echo $i
else
echo "All Services are now Stopped"
fi
done
I don't know if this syntax if fully operational or not as it doesn't work but this is the logic I want to do. What is the proper way to do this ?