Bash script to print `tail -f` when a file is moved or deleted

Currently, deleting, moving, or renaming a file that is running tail -fdoes nothing, and I would like to stop it. I read the man pages, and it seems that -f should interrupt when moving the file and that -F will follow the file, but on Mac OS X it seems that -f and -F are the same. How can I write a bash script that produces tail -f output cleanly after the file has been moved?

+4
source share
2 answers
  • On Linux, you can use tail --follow=name(and not just -fwhat is equivalent --follow=descriptor) to achieve what you want, but ONLY if the file is DELETED, and not moved - after deleting the file, an error message is displayed and tailexits (with code 1); Unfortunately, on the contrary, if the file is simply MOVED (renamed), it tailDOES NOT exit, which requires a software solution.
  • In OSX, you always need a software solution - whether the file is being moved or deleted.

a bash script to exit the tail as soon as the target file no longer exists (under its original name) - more reliable script formulations from @schellsan's own answer:

#!/usr/bin/env bash

tail -f "$1" &  # start tailing in the background
while [[ -f $1 ]]; do sleep 0.1; done # periodically check if target still exists
kill $! 2>/dev/null || : # kill tailing process, ignoring errors if already dead
  • Handles file names that require quotation marks (for example, names with embedded spaces).
  • - ; caveat: .

, , :

  • , , , , script ( , , , Control-C).
  • script, .
#!/usr/bin/env bash

# Set an exit trap to ensure that the tailing process
# - to be created below - is terminated, 
# no matter how this script exits.
trap '[[ -n $tailPid ]] && kill $tailPid 2>/dev/null' EXIT

# Start the tailing process in the background and
# record its PID.
tail -f "$1" & tailPid=$!

# Stay alive as long as the target file exists.
while [[ -f $1 ]]; do
  # Sleep a little.
  sleep 0.1
  # Exit if the tailing process died unexpectedly.
  kill -0 $tailPid 2>/dev/null || { tailPid=; exit; }
done
+7

, - , script, , , , .

#!/bin/bash

tail -f $1 &
pid=$!

while [ -f $1 ]
do
    if [ ! -f $1 ]
    then
        kill -9 $pid
    fi
done
+1

Source: https://habr.com/ru/post/1527150/


All Articles