ksh script to check if certain process is running

I have to kill the process "test" for a maintenance I do but want the script to check when it comes back up.

I can get what I want when I run this while loop:
while true;do ps -ef | grep test | grep -v grep | sed -e 's/^[ \t]*//';sleep 60;done

but I want the script to do it for me and as soon as the process is found I would like for it to exit. Please advise.

---------- Post updated at 02:43 AM ---------- Previous update was at 12:57 AM ----------

Nevermind I was able to figure it out.

TESTSTATUS=`ps -ef | grep test | grep -v grep | sed -e 's/^[ \t]*//'`

echo
echo
echo "\033[1;37 \033[1mAs soon as Test processes comes back up it will appear below:\033[0m\n"

until [[ -n $TESTSTATUS ]];do ps -ef | grep test | grep -v grep | sed -e 's/^[ \t]*//';done

Your loop will never finish as TESTSTATUS will not change its state as it's not reassigned.

1 Like

A simple "waitforit" script I use is

while [[ -z "${PIDS}" ]]; do
    sleep 30
    PIDS=$(pgrep "${*}")
done

ps -fp ${PIDS}

which is called as:

waitforit command

Just make sure man pgrep (linux) can find the process.

Ah yes you are correct. It just keeps going. How would I go about reassigning the variable?

By changing:

TESTSTATUS=`ps -ef | grep test | grep -v grep | sed -e 's/^[ \t]*//'`

echo
echo
echo "\033[1;37 \033[1mAs soon as Test processes comes back up it will appear below:\033[0m\n"

until [[ -n $TESTSTATUS ]];do ps -ef | grep test | grep -v grep | sed -e 's/^[ \t]*//';done

to:

TESTSTATUS=`ps -ef | grep test | grep -v grep | sed -e 's/^[ \t]*//'`

echo
echo
echo "\033[1;37 \033[1mAs soon as Test processes comes back up it will appear below:\033[0m\n"

until [[ -n $TESTSTATUS ]];do TESTSTATUS=`ps -ef | grep test | grep -v grep | sed -e 's/^[ \t]*//'`;done

Note that this will eat up a LOT of CPU cycles until your condition is met. Other people trying to get work done on your system (including those trying to start the process you're looking for) might be a lot happier if you at least stick a one second delay in your loop:

TESTSTATUS=`ps -ef | grep test | grep -v grep | sed -e 's/^[ \t]*//'`

echo
echo
echo "\033[1;37 \033[1mAs soon as Test processes comes back up it will appear below:\033[0m\n"

until [[ -n $TESTSTATUS ]];do sleep 1;TESTSTATUS=`ps -ef | grep test | grep -v grep | sed -e 's/^[ \t]*//'`;done
1 Like

Thank you! You've done it again Don! :slight_smile:

The following is most efficient; works in Linux and Solaris

pid=`pgrep test` &&
while [ -d /proc/$pid ]
do
 sleep 1
done