check-process.sh 1011 Bytes
#!/bin/bash

while getopts 'n:p:h' OPT
do
    case $OPT in
        n)  name=$OPTARG;;
        p)  port=$OPTARG;;
        h)  hlp="yes";;
        *)  unknown="yes";;
    esac
done

# usage
HELP="
    usage: $0 [ -n process name -p process port -h ]

        -n --> process name < value
        -p --> process port < value
        -h --> print this help screen
"
hlp=${hlp:=no}
if [ ${hlp} == "yes" ] || [ "${name}" == "" ]
then
    echo "${HELP}"
    exit 0
fi

function getpid(){
    pid=$(sudo ps -ef | grep "${name}" | grep -v grep | grep -v $0 | awk 'NR==1{print $2}' )
}

if [ "${name}" == "" ]
then
    exit 0
else
    process_flag=$(sudo ps -ef | grep ${name} | grep -v grep | grep -v $0 | wc -l)
fi

if [ "${port}" == "" ]
then
    port_flag=1
else
    port_flag=$(sudo netstat -lntp | grep ":${port} " | wc -l)
fi

if [ ${process_flag} -ge 1 ] && [ ${port_flag} -ge 1 ]
then
    echo "Ok: ${name} is ok,port is ${port}."
    exit 0
else
    echo "ERROR: ${name} is error,port is ${port}."
    exit 2
fi