Search code examples
linuxbashtail

How to exit tail -f and resume script


I have a simple script, that sets up logging, runs tail -f on the log file and then, after I exit tail, performs some cleanup. Basically something like this

echo 'monitoring started'
tail -f /var/log/some.log
echo 'never gets here'

Problem is, exiting tail by Ctrl+C breaks the script execution too, so cleanup is not called. Is there a way to 'properly' exit tail and resume script call? I found a few solutions based on saving PID and killing it by timeout, but that's not what I want here, I may need the monitoring for a few minutes or few hours, so I'd like to have a manual switch.


Solution

  • You can do something like this

    echo "monitoring started"
    tail -f /var/log/some.log & #execute tail in background
    read -sn 1 #wait for user input
    kill %1 #kill the first background progress, i.e. tail
    echo "Is reached"