Search code examples
bashps

reading variables to ps ax script


Hi I've been searching on the forum but I cant seem to get this right. I am trying to create a script that asks the user which process they are searching for then returns with a 1 if the process is running.

This works:

#!/bin/bash
SERVICE='httpd'
if ps ax | grep -v grep | grep $SERVICE > /dev/null
then
echo "$SERVICE service running, everything is fine"
else
echo "$SERVICE is not running"
fi

I want to add this to the script:

 echo -e "please enter process name: \c"
 read word

for something like:

#!/bin/sh
echo -e "please enter process name: \c"
read input_variable
if ps ax | grep -v grep | grep $varname > /dev/null
then
echo "$SERVICE service running, everything is fine"
else
echo "$SERVICE is not running"
fi

Solution

  • Use pgrep to search for processes:

    read process_name
    if pgrep "${process_name}" >/dev/null 2>&1 ; then
        "echo ${process_name} found"
    else
        "echo ${process_name} not found"
    fi