I am executing this command:

tail -f rest.log | while read 
    [[ "${LOGLINE}" == *"Finished building"* ]] && pkill -P $$ tail

It will read a log file until string 'Finished building' appears in the file. If so, it will kill the tail command. Sometimes the string will never appear. For this case I want to quit the loop after a certain time. Kind of a timeout. Lets say it should stop searching the string after 5 minutes. How can I achieve this? I tried to use timeout in front of the first tail command, which did not work for me.

  • 2
    How did it not work? It works fine here: timeout 3s tail -f /etc/hosts | while read FOO; do sleep 5s; done results in Terminated 3 seconds later.
    – Jeff Schaller
    Apr 9 '19 at 13:12
  • Yeah timeout command's working fine! # timeout 1m tail -f rest.log | while read ; LOGLINE; do [[ "${LOGLINE}" == *"Finished building"* ]] && pkill -P $$ tail; done Terminated -- Its terminated after 1 minute.
    – ss_iwe
    Apr 9 '19 at 13:14

Try this: read has built in timeout option -t!

while read -t 10 LOGLINE 
  [[ "${LOGLINE}" == *"Finished building"* ]] && pkill -P $$ tail

The above terminates after 10 seconds. Mention your required timeout in seconds. For more refer man read

read [-ers] [-a aname] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]

Another option is to use the timeout command having the while loop in another script:

timeout 300 script_that_searches_for_finished_build.sh

The script will run for 5 minutes and stop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.