- 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" &
while [[ -f $1 ]]; do sleep 0.1; done
kill $! 2>/dev/null || :
- 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