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:
secondsbuilt-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/fdreference, or similar) which, when read from, contain output command contained therein. see bashfaq #24 discussion of why more suitable pipingread.
Comments
Post a Comment