Shell function to tail a log file for a specific string for a specific time

后端 未结 5 1320
情话喂你
情话喂你 2020-12-29 08:39

I need to the following things to make sure my application server is

  1. Tail a log file for a specific string
  2. Remain blocked until that string is printe
5条回答
  •  执念已碎
    2020-12-29 08:45

    The accepted answer doesn't work and will never exit (because althouth read -t exits, the prior pipe commands (tail -f | grep) will only be notified of read -t exit when they try to write to output, which never happens until the string matches).

    A one-liner is probably feasible, but here are scripted (working) approaches. Logic is the same for each one, they use kill to terminate the current script after the timeout. Perl is probably more widely available than gawk/read -t

    #!/bin/bash
    
    FILE="$1"
    MATCH="$2"
    
    # Uses read -t, kill after timeout
    #tail -f "$F" | grep "$MATCH" | (read -t 1 a ; kill $$)
    
    # Uses gawk read timeout ability (not available in awk)
    #tail -f "$F" | grep "$MATCH" | gawk "BEGIN {PROCINFO[\"/dev/stdin\", \"READ_TIMEOUT\"] = 1000;getline < \"/dev/stdin\"; system(\"kill $$\")}"
    
    # Uses perl & alarm signal
    #tail -f "$F" | grep "$MATCH" | perl -e "\$SIG{ALRM} = sub { `kill $$`;exit; };alarm(1);<>;"
    

提交回复
热议问题