将 SYSTEMCTL 状态的 grep 搜索结果转换为 IF 条件



首先,感谢您对此进行调查!

我对 bash 脚本非常熟悉,我想要实现的是:我目前必须经常在工作中重新启动一些服务,我正在尝试创建一个 scrip 来自动化它,我设法创建了所有内容,但我还想创建一个条件,如果 systemctl 状态 = 非活动,则回显"好的,很好,一切都很好"所以让我们继续,但如果没有,那么回显"重新启动将在 10 秒内重新触发";我正在使用 grep 从服务上的 systemctl 状态(由 bluetooth.service 下面表示(中找到文本"活动:活动(正在运行(或"活动:非活动(死(":

#!/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"

提前感谢所有的帮助和支持! :)

systemctl is-active

root@freeswitch:~# systemctl is-active dialer
inactive

我建议使用systemctl show <service-name> --no-page而不是解析状态输出:

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

最新更新