How to search a text file for a specific line and then kill a process when finding it with bash?

StackOverflow https://stackoverflow.com/questions/19828029

  •  17-07-2022
  •  | 
  •  

Question

I have very little experience with scripting, but I'd like to get into it.

Basically, this is for a StarMade server, as its java process doesn't shut down on a crash but rather remains running, so it becomes hard to properly detect crashes, and these occur very frequently.

What I want though, is to find a specific line in the server log file that indicates the server is frozen/has crashed, and kill the process after reading this line, then another script would start it up again (got that part already). The log file continuously gets updated by the server, so the script basically has to "watch" the file somehow.

I couldn't find any exact matches for this idea anywhere, but I tried to scrape something together from many sources, although I'm pretty sure it's entirely wrong:

#!/bin/bash
cd "$(dirname "$0")"
if grep -Fxq "[SERVER] SERVER SHUTDOWN" log.txt.0
then
    kill -9 $(pidof StarMade.jar)
else
    false
fi

As far as I can tell, this should continuously check the file log.txt.0 to find direct matches with "[SERVER] SERVER SHUTDOWN" and kill the server process when it does, or do nothing when it doesn't, is this a correct way to do it? I don't want to break things by stupid mistakes.

Was it helpful?

Solution

Try this:

if ( grep -Fxq "[SERVER] SERVER SHUTDOWN" log.txt.0 > /dev/null ); then
    kill -9 $(pidof StarMade.jar)
fi
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top