下面是正确的实现方式,把所有的查询到ps相关信息都给获取到,#!/bin/bashsource /etc/profile
MGT_Process=('/sbin/nginx$' '/nginx/etcd_proxy.conf$' '/nginx/nginx.conf$')
NGX_Process=('/sbin/nginx$' '/nginx/etcproxy.conf$' '/nginx/nginx.conf$')
LVS_Process=('/sbin/nginx$' /nginx/proxy.conf' 'keepalived')
checkLVSProcess(){
for process in ${LVS_Process[*]};do
i=1
cmd_tmp=""
exist_flag=0
OLD_IFS="$IFS"
IFS=$'
'
for line in `ps -eo user,pid,lstart,stat,%cpu,%mem,command|grep $process |grep -v grep`
do
IFS="$OLD_IFS"
for list in $line
do
arr_tmp[$i]=$list
if [ $i -gt 10 ];then
cmd_tmp=$cmd_tmp${arr_tmp[$i]}" "
fi
i=$[$i+1]
done
exist_flag=1
echo "state=ative,user=${arr_tmp[1]},pid=${arr_tmp[2]},stat=${arr_tmp[8]},cpu=${arr_tmp[9]},mem=${arr_tmp[10]},command=${cmd_tmp}"
cmd_tmp=""
i=1
done
if [ $exist_flag -eq 0 ];then
echo "state=noative,user=${arr_tmp[1]},pid=${arr_tmp[2]},stat=${arr_tmp[8]},cpu=${arr_tmp[9]},mem=${arr_tmp[10]},command=${cmd_tmp}"
fi
arr_tmp=()
done
}
process_Check(){
if [ -d /usr/local/NSP/etc/lua ];then
echo "==Process_Monitor(Process_Cmd)"
checkLVSProcess
fi
}
process_Check在这里要特别说明一下,while read line ,如果while readline 用的是管道的方法,在循环中赋值的变量是无法传值给外部的,因为管道用的是subshell (子进程),也就是while 循环执行的语句是在另外一个进程中执行的,所以赋值无法传给循环外部。这个就是网上有很多人说,为什么时候while循环赋值有效,有时却不起效,请注意是不是在同一进程执行。示例#!/bin/bash
source /etc/profile
MGT_Process=('/sbin/nginx$' '/nginx/etcd_proxy.conf$' '/nginx/nginx.conf$')
NGX_Process=('/sbin/nginx$' '/nginx/etcproxy.conf$' '/nginx/nginx.conf$')
LVS_Process=('/sbin/nginx$' /nginx/proxy.conf' 'keepalived')
checkLVSProcess(){
for process in ${LVS_Process[*]};do
i=1
cmd_tmp=""
exist_flag=0
ps -eo user,pid,lstart,stat,%cpu,%mem,command|grep $process |grep -v grep |while read line
do
for list in $line
do
arr_tmp[$i]=$list
if [ $i -gt 10 ];then
cmd_tmp=$cmd_tmp${arr_tmp[$i]}" "
fi
i=$[$i+1]
done
exist_flag=1
echo "state=ative,user=${arr_tmp[1]},pid=${arr_tmp[2]},stat=${arr_tmp[8]},cpu=${arr_tmp[9]},mem=${arr_tmp[10]},command=${cmd_tmp}"
cmd_tmp=""
done
if [ "outer:"$exist_flag -eq 0 ];then
echo "state=noative,user=${arr_tmp[1]},pid=${arr_tmp[2]},stat=${arr_tmp[8]},cpu=${arr_tmp[9]},mem=${arr_tmp[10]},command=${cmd_tmp}"
fi
arr_tmp=()
done
}