Jonathan Jonathan - 1 year ago 120
Linux Question

Tail file till process exits

Going through the answers at superuser.

I'm trying to modify this to listen for multiple strings and echo custom messages such as ; 'Your server started successfully' etc

I'm also trying to tack it to another command i.e. pip

wait_str() {
local file="$1"; shift
local search_term="Successfully installed"; shift
local search_term2='Exception'
local wait_time="${1:-5m}"; shift # 5 minutes as default timeout

(timeout $wait_time tail -F -n0 "$file" &) | grep -q "$search_term" && echo 'Custom success message' && return 0 || || grep -q "$search_term2" && echo 'Custom success message' && return 0

echo "Timeout of $wait_time reached. Unable to find '$search_term' or '$search_term2' in '$file'"
return 1

The usage I have in mind is:

pip install -r requirements.txt > /var/log/pip/dump.log && wait_str /var/log/pip/dump.log

To clarify, I'd like to get wait_str to stop tailing when pip exits, whether successfully or not.

Answer Source

Following is general answer and tail could be replaced by any command that result in stream of lines.

IF different string needs different actions then use following:

tail -f var/log/pip/dump.log |awk '/condition1/ {action for condition-1} /condition-2/ {action for condition-2} .....' 

If multiple conditions need same action them ,separate them using OR operator :

tail -f var/log/pip/dump.log |awk '/condition-1/ || /condition-2/ || /condition-n/ {take this action}'

Based on comments : Single awk can do this.

tail -f /path/to/file |awk '/Exception/{ print "Worked"} /compiler/{ print "worked"}'  


tail -f /path/to/file | awk '/Exception/||/compiler/{ print "worked"}' 

OR Exit if match is found

tail -f logfile |awk '/Exception/||/compiler/{ print "worked";exit}'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download