First of all, thanks for looking into this!
I am very newbie at bash scripting what I am trying to achieve is: I currently have to restart some services at my work quite often and I am trying to create a scrip to automatise it, I managed to create everything but I want also to create a conditional where if the systemctl status = inactive then echo "ok, fine, all good" so lets proceed but if not, then echo "re-start will be re-atempted in 10secs"; I am using grep to find the text "active: active (running) or "active: inactive (dead) from the systemctl status on the service (represented by bluetooth.service bellow):
#!/bin/bash
#Restarting bluetooth.service
clear
active_stop="Active: stopped (dead)"
echo "This script will RESTART the following service: Bluetooth.Service"
echo -e "State the REASON for the RESTART: " >> /home/sjadmin/SYS_RESTART/ARCHIVE/sysrestart.log
read -p "Press ENTER to continue or CTRL + C to cancel"
sudo systemctl stop bluetooth.service |grep active IF [[grep -q=$active_stop]]
then read -p "Service STOPPED, please confirm status bellow, press ENTER to continue..."
else read -p "Action failed";
fi
sudo systemctl status bluetooth.service |grep status1="$(Active: active (running))" >> /home/sjadmin/SYS_RESTART/ARCHIVE/sysrestart.log
sudo systemctl status bluetooth.service |grep active
echo "Service will be RESTARTED in 5 MINUTES, PLEASE DO NOT DISCONECT FROM THE SYSTEM..."
sleep 10s
sudo systemctl start bluetooth.service
read -p "Service RE-STARTED, please confirm status bellow, press ENTER to continue..."
sudo systemctl status bluetooth.service |grep active >> /home/sjadmin/SYS_RESTART/ARCHIVE/sysrestart.log
sudo systemctl status bluetooth.service |grep active
echo "System RESTARTED CORRECTLY, please find the log at the SYS_RESTART/ARCHIVE folder"
Thanks in advance for all the help and the support! :)
I would suggest to use systemctl show <service-name> --no-page
instead of parsing status output:
status="$(systemctl show bluetooth.service --no-page)"
status_text=$(echo "${status}" | grep 'StatusText=' | cut -f2 -d=)
if [ "${status_text}" == "Running" ]
then
echo "It's running"
else
echo "Not running"
fi
active_state=$(echo "${status}" | grep 'ActiveState=' | cut -f2 -d=)
if [ "${active_state}" == "active" ]
then
echo "It's active"
else
echo "Not active"
fi