這是我的 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