kill a process if grep match is found

Hi,

I need something unusual, I guess. I need to start a process, and if that process displays a specific error message, I need to kill that process and restart it.

Something like:

startprocess | grep -i "This is the specific error message" && kill $pidof(startprocess)

Explanation, I need to start the process, check if it echoes any messages and if any of them is the one that I'm waiting, I need to kill that process.

Restarting of the process I can do putting all this in a while loop or something.

Is this possible at all? Is there any easier way to accomplish the same thing?

Thanks for any help in advance.

#!/bin/bash

rm -f /tmp/procfifo
mkfifo /tmp/procfifo



startprocess >/tmp/procfifo &
PID=$!

while read LINE
do
        if [[ "$LINE" == *PATTERN* ]]
        then
                kill "$PID"
                break
        fi
done < /tmp/procfifo



rm -f /tmp/procfifo

wait "$PID"
echo "Process returned $?"
1 Like

If you're shooting for a one-liner then this could work:

startprocess > /tmp/output && [ $(grep <error message> /tmp/outputfile) ] && pkill <process_name> || echo "No Error Occurred"

Just my one and half cents. Economy you know.

Good luck.

1 Like

You guys are great!!! :)))
The only thing I couldn't get to work is *pattern* (substring is needed), but I'll try to google for an example :slight_smile:
Thanks alot

*pattern* will work if you have a shell that supports it:

$ [[ "ABCDEFG" == *DEF* ]] && echo "DEF matches"
DEF matches

$ [[ "ABCDEFG" == *DJQ* ]] && echo "DJQ matches

$

If you don't, it would've been nice to know what shell you had an hour ago.