How to tail -f the latest log file with a given pattern

后端 未结 5 717
深忆病人
深忆病人 2020-12-30 08:29

I work with some log system which creates a log file every hour, like follows:

SoftwareLog.2010-08-01-08
SoftwareLog.2010-08-01-09
SoftwareLog.2010-08-01-10
         


        
5条回答
  •  别那么骄傲
    2020-12-30 09:03

    #!/bin/bash
    
    PATTERN="$1"
    
    # Try to make sure sub-shells exit when we do.
    trap "kill -9 -- -$BASHPID" SIGINT SIGTERM EXIT
    
    PID=0
    OLD_FILES=""
    while true; do
      FILES="$(echo $PATTERN)"
      if test "$FILES" != "$OLD_FILES"; then
        if test "$PID" != "0"; then
          kill $PID
          PID=0
        fi
        if test "$FILES" != "$PATTERN" || test -f "$PATTERN"; then
          tail --pid=$$ -n 0 -F $PATTERN &
          PID=$!
        fi
      fi
      OLD_FILES="$FILES"
      sleep 1
    done
    

    Then run it as: tail.sh 'SoftwareLog*'

    The script will lose some log lines if the logs are written to between checks. But at least it's a single script, with no symlinks required.

提交回复
热议问题