Check if a process is running using Bash

后端 未结 7 934
被撕碎了的回忆
被撕碎了的回忆 2020-12-19 18:53

I am trying to check if a process is running with the code below:

SERVICE=\"./yowsup/yowsup-cli\"
RESULT=`ps aux | grep $SERVICE`

if [ \"${RESULT:-null}\" =         


        
7条回答
  •  眼角桃花
    2020-12-19 19:34

    ## bash
    
    ## function to check if a process is alive and running:
    
    _isRunning() {
        ps -o comm= -C "$1" 2>/dev/null | grep -x "$1" >/dev/null 2>&1
    }
    
    ## example 1: checking if "gedit" is running
    
    if _isRunning gedit; then
        echo "gedit is running"
    else
        echo "gedit is not running"
    fi
    
    ## example 2: start lxpanel if it is not there
    
    if ! _isRunning lxpanel; then
        lxpanel &
    fi
    
    ## or
    
    _isRunning lxpanel || (lxpanel &)
    

    Note: pgrep -x lxpanel or pidof lxpanel still reports that lxpanel is running even when it is defunct (zombie); so to get alive-and-running process, we need to use ps and grep

提交回复
热议问题