英文:
Systemctl Services start with Bash Script
问题
我有一个启动脚本,检查服务是否处于活动/非活动状态,并在必要时启动它:
!/usr/bin/sh
# 设置捕获错误的陷阱
trap 'catch $? $LINENO' ERR
function catch() {
echo "发生错误,行号:$2,退出状态:$1"
exit 1
}
# 设置脚本在错误发生时立即退出
#set -e
# 定义服务列表
SERVICES=(service1 service2 service3)
for service in $SERVICES
do
echo "检查 $service 状态"
STATUS="$(systemctl is-active $service)"
echo "状态为 ${STATUS}"
RUNNING="$(systemctl show -p SubState $service | cut -d'=' -f2)"
echo "运行状态为 $RUNNING"
if [ "${STATUS}" = "active" ]; then
echo "$service 服务处于活动状态"
if [ "${RUNNING}" = "running" ]; then
echo "$service 服务正在运行"
else
echo "$service 服务未运行"
fi
else
echo "对于 $service 返回 ${STATUS}。正在启动..."
systemctl start $service
echo "$service 已启动"
fi
done
运行 'sh start.sh' 时,我得到 '发生错误,行号:19,退出状态:3'。这是什么原因?我没有看到任何语法错误。
英文:
I have a start script that checks if the service is active/inactive and starts it if necessary:
!/usr/bin/sh
# Set up the trap to catch errors
trap 'catch $? $LINENO' ERR
function catch() {
echo "An error occurred on line $2 with exit status $1"
exit 1
}
# Set the script to exit immediately on errors
#set -e
# define the services list
SERVICES=(service1 service2 service3)
for service in $SERVICES
do
echo "Checking $service status"
STATUS="$(systemctl is-active $service)"
echo "status is ${STATUS}"
RUNNING="$(systemctl show -p SubState $service | cut -d'=' -f2)"
echo "Running status is $RUNNING"
if [ "${STATUS}" = "active" ]; then
echo "$service Service is Active"
if [ "${RUNNING}" = "running" ]; then
echo "$service Service is Running"
else
echo "$service Service Not Running"
fi
else
echo "Returned ${STATUS} for $service. Starting it... "
systemctl start $service
echo "$service started"
fi
done
When running 'sh start.sh' I get 'An error occurred on line 19 with exit status 3'
What is the cause for it ? I do not see any syntax errors.
答案1
得分: 1
Systemctl 手册页:如果没有活跃单元,则 is-active 可以返回非零的退出代码。
is-active 模式...
检查指定的单元是否有任何活跃(即运行中)。如果至少有一个单元活跃,则返回退出代码 0,
否则返回非零代码。除非指定 --quiet,否则还会将当前单元状态输出到标准输出。
https://www.freedesktop.org/software/systemd/man/systemctl.html#Exit%20status
英文:
Systemctl man page: is-active can return an exit code non-zero if no active
is-active PATTERN...
Check whether any of the specified units are active (i.e.
running). Returns an exit code 0 if at least one is active,
or non-zero otherwise. Unless --quiet is specified, this will
also print the current unit state to standard output.
https://www.freedesktop.org/software/systemd/man/systemctl.html#Exit%20status
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论