views:

60

answers:

2

I have a couple of scripts to control some applications (start/stop/list/etc). Currently my "stop" script just sends an interrupt signal to an application, but I'd like to have more feedback about what application does when it is shutting down. Ideally, I'd like to start tailing its log, then send an interrupt signal and then keep tailing that log until the application stops.

How to do this with a shell script?

+6  A: 

For just tailing a log file until a certain process stops (using tail from GNU coreutils):

do_something > logfile &
tail --pid $! -f logfile

UPDATE The above contains a race condition: In case do_something spews many lines into logfile, the tail will skip all of them but the last few. To avoid that and always have tail print the complete logfile, add a -n +1 parameter to the tail call (that is even POSIX tail(1)):

do_something > logfile &
tail --pid $! -n +1 -f logfile
ndim
Cool, I didn't know of the `--pid` flag!
Joachim Sauer
Well, e.g. POSIX `tail` or busybox `tail` do not have the `--pid` flag, so you cannot widely rely on it actually being present.
ndim
@ndim: I see, but GNU coreutils is "widely" enough for me ;-)
Joachim Sauer
A: 

Here's a Bash script that works without --pid. Change $log_file and $p_name to suit your need:

#!/bin/bash

log_file="/var/log/messages"
p_name="firefox"

tail -n10 $log_file
curr_line="$(tail -n1 $log_file)"
last_line="$(tail -n1 $log_file)"

while [ $(ps aux | grep -v grep | grep $p_name | wc -l) -gt 0 ] 
do
        curr_line="$(tail -n1 $log_file)"
        if [ "$curr_line" != "$last_line" ]
        then
                echo $curr_line
                last_line=$curr_line
        fi  
done
echo "[*] $p_name exited !!"
Babil