Your script has numerous errors. Probably try https://shellcheck.net/ before asking for human assistance.
You need to update the value of the variable inside the loop.
You seem to be reinventing pgrep
, poorly.
(The regular expression tail*
looks for tai
, tail
, taill
, tailll
... What do you actually hope this should do?)
To break out of a loop and continue outside, use break
.
The braces around your loop are superfluous. This is shell script, not C or Perl.
You are probably looking for something like
while true; do
if ! pgrep tail; then
echo "Sending mails ...."
break
fi
done
This avoids the use of a variable entirely; if you do need a variable, don't use upper case for your private variables.
Based on information in comments, if you have a number of processes like
tail -2000f /var/log/log.{1..10}
and no way to check their PIDs any longer, you might want to use fuser
to tell you when none of them are running any longer:
while true; do
fuser /var/log/log.{1..10} || break
sleep 60
done
echo All processes are gone now.
Unfortunately, fuser
does not reliably set its exit code - test on the command line (run tail -f $HOME/.bash_profile
in one window and then fuser $HOME/.bash_profile && echo yes
in another; then quit the tail
and run fuser
again. If it still prints yes
you need something more.)
On MacOS, I found that fuser -u
will print parentheses when the files are still open, and not when not:
while true; do
fuser -u /var/log/log.{1..10} 2>&1 | grep -q '[()]' || break
sleep 60
done
On Debian, fuser
is in the package psmisc
, and does set its exit code properly. You will probably also want to use the -s
option to make it run quietly.
Notice also the addition of a sleep
to avoid checking hundreds or thousands of times per second. You would probably want to make the same change to the original solution. How long to wait between iterations depends on how urgently you need the notification, and how heavy the operation to check the condition is. Even sleep 0.1
would be a significant improvement over the sleepless spin lock.