这是我的 bash 脚本。它所做的只是检查服务是否已启动以及某些进程是否按预期运行。
它突然以“终止”消息结束。我尝试用该标志对其进行调试set -x
,但我仍然不知道出了什么问题。 Stack Overflow 和 Google 没有向我展示任何其他人遇到类似的问题。
该脚本的权限为 755。由于显而易见的原因,某些命令被混淆了。
#!/bin/bash
set -x
DAEMON_BIN=/etc/init.d/init-god
DAEMON_BIN_START="${DAEMON_BIN} start"
DAEMON_BIN_STOP="${DAEMON_BIN} stop"
SOME_VARIABLE="foo"
CHEF_CONFIG_FILE_PATH="/path/to/file"
NODE_INFO_FILE="/mnt/node_info/properties"
function get_key_value (){
value=$(grep -Po "(?<=^${1}:).*" ${NODE_INFO_FILE})
echo $value;
}
eval $DAEMON_BIN_STOP
nohup pkill DAEMON &> /dev/null
nohup pkill -f resque &> /dev/null
eval $DAEMON_BIN_START
sleep 15
PROCESS_COUNT=`ps aux | awk '/[p]rocess-name/' | wc -l`
NODE_NAME=`get_key_value node_name`
if [[ $NODE_NAME -eq $SOME_VARIABLE && $PROCESS_COUNT -eq 1 ]]; then
echo "DAEMON and scheduler are running fine." ;
else
echo "A problem with DAEMON has occured." ;
fi
EXPECTED_PROCESS_COUNT=`get_key_value no_of_workers`
ACTUAL_WORKER_COUNT=`ps ax | grep [r]esque-[0-9]`
if [[ $EXPECTED_PROCESS_COUNT -eq $ACTUAL_WORKER_COUNT ]]; then
echo "Correct Number of workers initialized." ;
else
echo "More workers exist than are permitted." ;
fi
for (( i=0; i<${EXPECTED_PROCESS_COUNT}; i++ )); do
WORKER_NAME=`get_key_value worker_${i}`
COUNT=`ps ax | grep ${WORKER_NAME} | grep -v grep | wc -l`
if [[ $COUNT -eq 1 ]]; then
#statements
echo "${WORKER_NAME} is running."
else
echo "${WORKER_NAME} may not be running or might have more than 1 copies."
fi
done
脚本的调试输出如下:
+ DAEMON_BIN=/etc/init.d/init-god
+ DAEMON_BIN_START='/etc/init.d/init-god start'
+ DAEMON_BIN_STOP='/etc/init.d/init-god stop'
+ SOME_VARIABLE=foo
+ CHEF_CONFIG_FILE_PATH=/path/to/file
+ NODE_INFO_FILE=/mnt/node_info/properties
+ eval /etc/init.d/init-god stop
++ /etc/init.d/init-god stop
.
Stopped all watches
Stopped god
+ nohup pkill DAEMON
+ nohup pkill -f resque
Terminated
为什么此脚本退出时显示“已终止”消息?我应该怎么做才能防止这种情况发生?
答案1
当您调用它时pkill -f resque
,它也与您的脚本匹配,并向其发送 SIGTERM。如果您无法对pkill
命令添加其他限制(例如更精确的匹配),则需要一次终止一个 PID,以确保脚本不会终止自身。这是一个例子:
pids=( $(pgrep -f resque) )
for pid in "${pids[@]}"; do
if [[ $pid != $$ ]]; then
kill "$pid"
fi
done