Alex Rivera | Logout

Ending tail -f started in a shell script

Asked 2010-01-11T11:21:04.083
29

I have the following.

  1. A Java process writing logs to the stdout
  2. A shell script starting the Java process
  3. Another shell script which executes the previous one and redirects the log
  4. I check the log file with the tail -f command for the success message.

Even if I have exit 0 in the code I cannot end the tail -f process.

Which doesn't let my script to finish. Is there any other way of doing this in Bash?

The code looks like the following.

function startServer() {
  touch logfile
  startJavaprocess > logfile &

  tail -f logfile | while read line 
  do
    if echo $line | grep -q 'Started'; then
      echo 'Server Started'
      exit 0
    fi
  done
}
Edit
Report

2 Answers

2

Capture the pid of the background process

pid=$!

Use tail's --pid=PID option, so that it terminates after the process having pid $PID terminates.

answered 2010-01-11T11:35:49.443
1

Rather than exiting the process, you can instead find the process ID of the tail -f process and kill it (a kill -9 would even be safe here if you're sure the log file has finished).

That way, the while read line will terminate naturally and you won't need to exit.

Or, since you're not really using the tail to output to the screen, you could also try the more old-school:

grep -q 'Started' logfile
while [[ $? -ne 0 ]] ; do
    sleep 1
    grep -q 'Started' logfile
done
answered 2010-01-11T11:35:28.190

Your Answer