Linux Script to check if process is running and act on the result

前端 未结 7 1872
孤独总比滥情好
孤独总比滥情好 2020-11-29 23:38

I have a process that fails regularly & sometimes starts duplicate instances..

When I run: ps x |grep -v grep |grep -c \"processname\" I will get: <

7条回答
  •  一向
    一向 (楼主)
    2020-11-30 00:25

    In case you're looking for a more modern way to check to see if a service is running (this will not work for just any old process), then systemctl might be what you're looking for.

    Here's the basic command:

    systemctl show --property=ActiveState your_service_here
    

    Which will yield very simple output (one of the following two lines will appear depending on whether the service is running or not running):

    ActiveState=active
    ActiveState=inactive
    

    And if you'd like to know all of the properties you can get:

    systemctl show --all your_service_here
    

    If you prefer that alphabetized:

    systemctl show --all your_service_here | sort
    

    And the full code to act on it:

    service=$1
    result=`systemctl show --property=ActiveState $service`
    if [[ "$result" == 'ActiveState=active' ]]; then
        echo "$service is running" # Do something here
    else
        echo "$service is not running" # Do something else here
    fi 
    

提交回复
热议问题