bash - Terminate tail command after timeout -


i'm capturing stdout (log) in file using tail -f file_name save specific string grep , sed (to exit tail) :

tail -f log.txt | sed /'info'/q |  grep 'info' > info_file.txt 

this works fine, want terminate command in case not find pattern (info) in log file after time

i want (which not work) exit script after timeout (60sec):

tail -f log.txt | sed /'info'/q |  grep 'info' | read -t 60 

any suggestions?

since want capture 1 line:

#!/bin/bash ifs= read -r -t 60 line < <(tail -f log.txt | awk '/info/ { print; exit; }') printf '%s\n' "$line" >info_file.txt 

for more general case, want capture more 1 line, following uses no external commands other tail:

#!/usr/bin/env bash end_time=$(( seconds + 60 )) while (( seconds < end_time ));   ifs= read -t 1 -r line && [[ $line = *info* ]] && printf '%s\n' "$line" done < <(tail -f log.txt) 

a few notes:

  • seconds built-in variable in bash which, when read, retrieve time in seconds since shell started. (it loses behavior after being target of assignment -- avoiding such mishaps part of why posix variable-naming conventions reserving names lowercase characters application use valuable).
  • (( )) creates arithmetic context; content within treated integer math.
  • <( ) process substitution; evaluates name of file-like object (named pipe, /dev/fd reference, or similar) which, when read from, contain output command contained therein. see bashfaq #24 discussion of why more suitable piping read.

Comments

Popular posts from this blog

c# - Update a combobox from a presenter (MVP) -

How to understand 2 main() functions after using uftrace to profile the C++ program? -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -