如何为日志创建shell脚本

时间:2010-04-09 09:31:51

标签: linux shell

我正在观看我的日志文件,如tail -f,我不时地按下键并点击返回以便日志中的新更改打印到控制台,如何在日志文件中更改时自行打印发生?这是要求:

START loop
1. Check file.log
2. If file.log has changed print the changes
3. else print nothing
END

我为java执行了类似的操作:

import java.io.FileInputStream;
import java.io.DataInputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;

class LogWatch {
    public static void main(String args[]) {
        try {

            FileInputStream fstream = new FileInputStream("C:\\file.log");

            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String line;

            while (true) {

                line = br.readLine();
                if (line == null) {
                    Thread.sleep(500);
                } else {
                    System.out.println(line);
                }

            }

        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}

这是不必要的开销,因为这可以通过shell脚本完成,有没有人有任何建议怎么做?

1 个答案:

答案 0 :(得分:4)

使用-F代替-f

假设-f没有'工作,因为你正在触及logrotate并且没有提到必须杀死之前的尾部实例。

 -f      The -f option causes tail to not stop when end of file is
         reached, but rather to wait for additional data to be appended to
         the input.  The -f option is ignored if the standard input is a
         pipe, but not if it is a FIFO.

 -F      The -F option implies the -f option, but tail will also check to
         see if the file being followed has been renamed or rotated.  The
         file is closed and reopened when tail detects that the filename
         being read from has a new inode number.  The -F option is ignored
         if reading from standard input rather than a file.
相关问题