George L
George L

Reputation: 1738

Exiting while loop bash script from tail

I have a script that tails a log file, and then uploads the line. I would like to have it exit as soon as the first line is read:

#!/bin/bash

tail -n0 -F "$1" | while read LINE; do
  (echo "$LINE" | grep -e "$3") && curl -X POST --silent --data-urlencode \
    "payload={\"text\": \"$(echo $LINE | sed "s/\"/'/g")\"}" "$2";
done

Upvotes: 0

Views: 386

Answers (2)

George L
George L

Reputation: 1738

The issue was the tail command wasn't getting killed. A slightly modified version of my script (I didn't end up needing the echo to stdout)

#!/bin/bash

tail -n0 -F "$1" | while read LINE; do
    curl -X POST --data-urlencode "payload={\"text\": \"$(echo $LINE | sed "s/\"/'/g")\"}" "$2" && pkill -P $$ tail
done

This answer helped as well: https://superuser.com/questions/270529/monitoring-a-file-until-a-string-is-found

Upvotes: 1

MrJLP
MrJLP

Reputation: 998

If you want to exit as soon as the first line is uploaded you can just add a break:

#!/bin/bash

tail -n0 -F "$1" | while read LINE; do
  (echo "$LINE" | grep -e "$3") && curl -X POST --silent --data-urlencode \
    "payload={\"text\": \"$(echo $LINE | sed "s/\"/'/g")\"}" "$2" && break;
done

Upvotes: 1

Related Questions