1

I wrote a quick bash script that watches a log for a specific string and then exits. Except the problem is that I can still still script and its child "tail" process running after the script returns when I do a "ps -fu $user".

#!/bin/bash
####### MAIN #######

FILE=$1
MSG=""
while read LOGLINE
do
 if [[ "${LOGLINE}" == *"someString"* ]]; then 
     MSG=${LOGLINE}
     break
 fi
done < <(tail -f ${FILE}) 
pkill -P $$ tail
echo ${MSG}

I pass it a log file from an application that is continuously being written to. When I run this script, it will find the first instance of someString, echo it to stdout and exits. Except the tail process didn't seem to get killed nor did the script itself.

2
  • You would be better off with a tail -f $1 | while read LOGLINE and then echo $(MSG) and exit when the condition is met as opposed to break. Commented Jun 29, 2017 at 17:44
  • ... or more frankly, since tail readily exits on SIGPIPE, this is uncessarily backwards. Commented Jun 29, 2017 at 17:45

2 Answers 2

1

its important to understand why that is occurring.

issue is "break" used to exit the loop. the break is inside an if statement. exit would be more appropriate here as you want to exit all together.

also this part is not necessary and you just need to end with "done"

done < <(tail -f ${FILE})

you are never "done" with "tail" because you never asked for it in the first place.

since i presume your log is not trunkated at the beginning of the script, you are tailing for new content so you should pipe /or write tail to a temp file and then delete at exit of the script. either will work.

Sign up to request clarification or add additional context in comments.

Comments

0
#!/bin/bash
####### MAIN #######

FILE=$1
MSG=""
tail -f ${FILE} | while read LOGLINE
do
 if [[ "${LOGLINE}" == *"someString"* ]]; then 
     MSG=${LOGLINE}
     exit
 fi
done

The above solution reads the output from tail line by line continuously till the if condition is met. Once it is met, the whole script/process is exitted.

1 Comment

While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.