1 /* tail -- output the last part of file(s)
2 Copyright (C) 1989, 1990, 1991, 1995 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* Can display any amount of data, unlike the Unix version, which uses
19 a fixed size buffer and therefore can only deliver a limited number
23 -b Tail by N 512-byte blocks.
24 -c, --bytes=N[bkm] Tail by N bytes
25 [or 512-byte blocks, kilobytes, or megabytes].
26 -f, --follow Loop forever trying to read more characters at the
27 end of the file, on the assumption that the file
28 is growing. Ignored if reading from a pipe.
29 -n, --lines=N Tail by N lines.
30 -q, --quiet, --silent Never print filename headers.
31 -v, --verbose Always print filename headers.
33 If a number (N) starts with a `+', begin printing with the Nth item
34 from the start of each file, instead of from the end.
36 Reads from standard input if no files are given or when a filename of
38 By default, filename headers are printed only more than one file
40 By default, prints the last 10 lines (tail -n 10).
42 Original version by Paul Rubin <phr@ocf.berkeley.edu>.
43 Extensions by David MacKenzie <djm@gnu.ai.mit.edu>.
44 tail -f for multiple files by Ian Lance Taylor <ian@airs.com>. */
51 #include <sys/types.h>
58 /* Disable assertions. Some systems have broken assert macros. */
61 #define XWRITE(fd, buffer, n_bytes) \
65 assert ((n_bytes) >= 0); \
66 if (n_bytes > 0 && fwrite ((buffer), 1, (n_bytes), stdout) == 0) \
67 error (1, errno, "write error"); \
71 /* Number of items to tail. */
72 #define DEFAULT_N_LINES 10
74 /* Size of atomic reads. */
76 #define BUFSIZ (512 * 8)
79 /* If nonzero, interpret the numeric argument as the number of lines.
80 Otherwise, interpret it as the number of bytes. */
81 static int count_lines
;
83 /* If nonzero, read from the end of one file until killed. */
86 /* If nonzero, read from the end of multiple files until killed. */
87 static int forever_multiple
;
89 /* Array of file descriptors if forever_multiple is 1. */
90 static int *file_descs
;
92 /* Array of file sizes if forever_multiple is 1. */
93 static off_t
*file_sizes
;
95 /* If nonzero, count from start of file instead of end. */
96 static int from_start
;
98 /* If nonzero, print filename headers. */
99 static int print_headers
;
101 /* When to print the filename banners. */
104 multiple_files
, always
, never
110 static int file_lines ();
111 static int pipe_bytes ();
112 static int pipe_lines ();
113 static int start_bytes ();
114 static int start_lines ();
116 static int tail_bytes ();
117 static int tail_file ();
118 static int tail_lines ();
119 static long dump_remainder ();
120 static void tail_forever ();
121 static void usage ();
122 static void write_header ();
124 /* The name this program was run with. */
127 /* Nonzero if we have ever read standard input. */
128 static int have_read_stdin
;
130 /* If non-zero, display usage information and exit. */
131 static int show_help
;
133 /* If non-zero, print the version on standard output then exit. */
134 static int show_version
;
136 static struct option
const long_options
[] =
138 {"bytes", required_argument
, NULL
, 'c'},
139 {"follow", no_argument
, NULL
, 'f'},
140 {"lines", required_argument
, NULL
, 'n'},
141 {"quiet", no_argument
, NULL
, 'q'},
142 {"silent", no_argument
, NULL
, 'q'},
143 {"verbose", no_argument
, NULL
, 'v'},
144 {"help", no_argument
, &show_help
, 1},
145 {"version", no_argument
, &show_version
, 1},
154 enum header_mode header_mode
= multiple_files
;
156 /* If from_start, the number of items to skip before printing; otherwise,
157 the number of items at the end of the file to print. Initially, -1
158 means the value has not been set. */
161 int c
; /* Option character. */
162 int fileind
; /* Index in ARGV of first file name. */
164 program_name
= argv
[0];
167 forever
= forever_multiple
= from_start
= print_headers
= 0;
170 && ((argv
[1][0] == '-' && ISDIGIT (argv
[1][1]))
171 || (argv
[1][0] == '+' && (ISDIGIT (argv
[1][1]) || argv
[1][1] == 0))))
173 /* Old option syntax: a dash or plus, one or more digits (zero digits
174 are acceptable with a plus), and one or more option letters. */
175 if (argv
[1][0] == '+')
177 if (argv
[1][1] != '\0')
182 s_err
= xstrtol (++argv
[1], &p
, 0, &tmp_long
, "bkm");
184 if (s_err
== LONGINT_OVERFLOW
)
186 STRTOL_FATAL_ERROR (argv
[1], "argument", s_err
);
188 /* Parse any appended option letters. */
194 /* Interpret N_UNITS as # of bytes. */
211 header_mode
= always
;
215 error (0, 0, "unrecognized option `-%c'", *p
);
221 /* Make the options we just parsed invisible to getopt. */
227 while ((c
= getopt_long (argc
, argv
, "c:n:fqv", long_options
, (int *) 0))
249 s_err
= xstrtol (optarg
, NULL
, 0, &tmp_long
, "bkm");
251 tmp_long
= -tmp_long
;
253 if (s_err
!= LONGINT_OK
)
255 STRTOL_FATAL_ERROR (optarg
, (c
== 'n'
257 : "number of bytes"), s_err
);
270 header_mode
= always
;
280 printf ("tail - %s\n", version_string
);
288 n_units
= DEFAULT_N_LINES
;
290 /* To start printing with item N_UNITS from the start of the file, skip
291 N_UNITS - 1 items. `tail +0' is actually meaningless, but for Unix
292 compatibility it's treated the same as `tail +1'. */
301 if (optind
< argc
- 1 && forever
)
303 forever_multiple
= 1;
305 file_descs
= (int *) xmalloc ((argc
- optind
) * sizeof (int));
306 file_sizes
= (off_t
*) xmalloc ((argc
- optind
) * sizeof (off_t
));
309 if (header_mode
== always
310 || (header_mode
== multiple_files
&& optind
< argc
- 1))
314 exit_status
|= tail_file ("-", n_units
, 0);
316 for (; optind
< argc
; ++optind
)
317 exit_status
|= tail_file (argv
[optind
], n_units
, optind
- fileind
);
319 if (forever_multiple
)
320 tail_forever (argv
+ fileind
, argc
- fileind
);
322 if (have_read_stdin
&& close (0) < 0)
323 error (1, errno
, "-");
324 if (fclose (stdout
) == EOF
)
325 error (1, errno
, "write error");
329 /* Display the last N_UNITS units of file FILENAME.
330 "-" for FILENAME means the standard input.
331 FILENUM is this file's index in the list of files the user gave.
332 Return 0 if successful, 1 if an error occurred. */
335 tail_file (filename
, n_units
, filenum
)
336 const char *filename
;
343 if (!strcmp (filename
, "-"))
346 filename
= "standard input";
348 write_header (filename
, NULL
);
349 errors
= tail (filename
, 0, n_units
);
350 if (forever_multiple
)
352 if (fstat (0, &stats
) < 0)
354 error (0, errno
, "standard input");
357 else if (!S_ISREG (stats
.st_mode
))
360 "standard input: cannot follow end of non-regular file");
364 file_descs
[filenum
] = -1;
367 file_descs
[filenum
] = 0;
368 file_sizes
[filenum
] = stats
.st_size
;
374 /* Not standard input. */
375 fd
= open (filename
, O_RDONLY
);
378 if (forever_multiple
)
379 file_descs
[filenum
] = -1;
380 error (0, errno
, "%s", filename
);
386 write_header (filename
, NULL
);
387 errors
= tail (filename
, fd
, n_units
);
388 if (forever_multiple
)
390 if (fstat (fd
, &stats
) < 0)
392 error (0, errno
, "%s", filename
);
395 else if (!S_ISREG (stats
.st_mode
))
397 error (0, 0, "%s: cannot follow end of non-regular file",
404 file_descs
[filenum
] = -1;
408 file_descs
[filenum
] = fd
;
409 file_sizes
[filenum
] = stats
.st_size
;
416 error (0, errno
, "%s", filename
);
427 write_header (filename
, comment
)
428 const char *filename
;
431 static int first_file
= 1;
433 printf ("%s==> %s%s%s <==\n", (first_file
? "" : "\n"), filename
,
434 (comment
? ": " : ""),
435 (comment
? comment
: ""));
439 /* Display the last N_UNITS units of file FILENAME, open for reading
441 Return 0 if successful, 1 if an error occurred. */
444 tail (filename
, fd
, n_units
)
445 const char *filename
;
450 return tail_lines (filename
, fd
, n_units
);
452 return tail_bytes (filename
, fd
, n_units
);
455 /* Output the last N_BYTES bytes of file FILENAME open for reading in FD.
456 Return 0 if successful, 1 if an error occurred. */
459 tail_bytes (filename
, fd
, n_bytes
)
460 const char *filename
;
466 /* FIXME: resolve this like in dd.c. */
467 /* Use fstat instead of checking for errno == ESPIPE because
468 lseek doesn't work on some special files but doesn't return an
470 if (fstat (fd
, &stats
))
472 error (0, errno
, "%s", filename
);
478 if (S_ISREG (stats
.st_mode
))
479 lseek (fd
, n_bytes
, SEEK_SET
);
480 else if (start_bytes (filename
, fd
, n_bytes
))
482 dump_remainder (filename
, fd
);
486 if (S_ISREG (stats
.st_mode
))
488 if (lseek (fd
, (off_t
) 0, SEEK_END
) <= n_bytes
)
489 /* The file is shorter than we want, or just the right size, so
490 print the whole file. */
491 lseek (fd
, (off_t
) 0, SEEK_SET
);
493 /* The file is longer than we want, so go back. */
494 lseek (fd
, -n_bytes
, SEEK_END
);
495 dump_remainder (filename
, fd
);
498 return pipe_bytes (filename
, fd
, n_bytes
);
503 /* Output the last N_LINES lines of file FILENAME open for reading in FD.
504 Return 0 if successful, 1 if an error occurred. */
507 tail_lines (filename
, fd
, n_lines
)
508 const char *filename
;
515 if (fstat (fd
, &stats
))
517 error (0, errno
, "%s", filename
);
523 if (start_lines (filename
, fd
, n_lines
))
525 dump_remainder (filename
, fd
);
529 if (S_ISREG (stats
.st_mode
))
531 length
= lseek (fd
, (off_t
) 0, SEEK_END
);
532 if (length
!= 0 && file_lines (filename
, fd
, n_lines
, length
))
534 dump_remainder (filename
, fd
);
537 return pipe_lines (filename
, fd
, n_lines
);
542 /* Print the last N_LINES lines from the end of file FD.
543 Go backward through the file, reading `BUFSIZ' bytes at a time (except
544 probably the first), until we hit the start of the file or have
545 read NUMBER newlines.
546 POS starts out as the length of the file (the offset of the last
547 byte of the file + 1).
548 Return 0 if successful, 1 if an error occurred. */
551 file_lines (filename
, fd
, n_lines
, pos
)
552 const char *filename
;
559 int i
; /* Index into `buffer' for scanning. */
564 /* Set `bytes_read' to the size of the last, probably partial, buffer;
565 0 < `bytes_read' <= `BUFSIZ'. */
566 bytes_read
= pos
% BUFSIZ
;
569 /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all
570 reads will be on block boundaries, which might increase efficiency. */
572 lseek (fd
, pos
, SEEK_SET
);
573 bytes_read
= safe_read (fd
, buffer
, bytes_read
);
574 if (bytes_read
== -1)
576 error (0, errno
, "%s", filename
);
580 /* Count the incomplete line on files that don't end with a newline. */
581 if (bytes_read
&& buffer
[bytes_read
- 1] != '\n')
586 /* Scan backward, counting the newlines in this bufferfull. */
587 for (i
= bytes_read
- 1; i
>= 0; i
--)
589 /* Have we counted the requested number of newlines yet? */
590 if (buffer
[i
] == '\n' && n_lines
-- == 0)
592 /* If this newline wasn't the last character in the buffer,
593 print the text after it. */
594 if (i
!= bytes_read
- 1)
595 XWRITE (STDOUT_FILENO
, &buffer
[i
+ 1], bytes_read
- (i
+ 1));
599 /* Not enough newlines in that bufferfull. */
602 /* Not enough lines in the file; print the entire file. */
603 lseek (fd
, (off_t
) 0, SEEK_SET
);
607 lseek (fd
, pos
, SEEK_SET
);
609 while ((bytes_read
= safe_read (fd
, buffer
, BUFSIZ
)) > 0);
610 if (bytes_read
== -1)
612 error (0, errno
, "%s", filename
);
618 /* Print the last N_LINES lines from the end of the standard input,
619 open for reading as pipe FD.
620 Buffer the text as a linked list of LBUFFERs, adding them as needed.
621 Return 0 if successful, 1 if an error occured. */
624 pipe_lines (filename
, fd
, n_lines
)
625 const char *filename
;
633 struct linebuffer
*next
;
635 typedef struct linebuffer LBUFFER
;
636 LBUFFER
*first
, *last
, *tmp
;
637 int i
; /* Index into buffers. */
638 int total_lines
= 0; /* Total number of newlines in all buffers. */
641 first
= last
= (LBUFFER
*) xmalloc (sizeof (LBUFFER
));
642 first
->nbytes
= first
->nlines
= 0;
644 tmp
= (LBUFFER
*) xmalloc (sizeof (LBUFFER
));
646 /* Input is always read into a fresh buffer. */
647 while ((tmp
->nbytes
= safe_read (fd
, tmp
->buffer
, BUFSIZ
)) > 0)
652 /* Count the number of newlines just read. */
653 for (i
= 0; i
< tmp
->nbytes
; i
++)
654 if (tmp
->buffer
[i
] == '\n')
656 total_lines
+= tmp
->nlines
;
658 /* If there is enough room in the last buffer read, just append the new
659 one to it. This is because when reading from a pipe, `nbytes' can
660 often be very small. */
661 if (tmp
->nbytes
+ last
->nbytes
< BUFSIZ
)
663 memcpy (&last
->buffer
[last
->nbytes
], tmp
->buffer
, tmp
->nbytes
);
664 last
->nbytes
+= tmp
->nbytes
;
665 last
->nlines
+= tmp
->nlines
;
669 /* If there's not enough room, link the new buffer onto the end of
670 the list, then either free up the oldest buffer for the next
671 read if that would leave enough lines, or else malloc a new one.
672 Some compaction mechanism is possible but probably not
674 last
= last
->next
= tmp
;
675 if (total_lines
- first
->nlines
> n_lines
)
678 total_lines
-= first
->nlines
;
682 tmp
= (LBUFFER
*) xmalloc (sizeof (LBUFFER
));
685 if (tmp
->nbytes
== -1)
687 error (0, errno
, "%s", filename
);
695 /* This prevents a core dump when the pipe contains no newlines. */
699 /* Count the incomplete line on files that don't end with a newline. */
700 if (last
->buffer
[last
->nbytes
- 1] != '\n')
706 /* Run through the list, printing lines. First, skip over unneeded
708 for (tmp
= first
; total_lines
- tmp
->nlines
> n_lines
; tmp
= tmp
->next
)
709 total_lines
-= tmp
->nlines
;
711 /* Find the correct beginning, then print the rest of the file. */
712 if (total_lines
> n_lines
)
716 /* Skip `total_lines' - `n_lines' newlines. We made sure that
717 `total_lines' - `n_lines' <= `tmp->nlines'. */
719 for (i
= total_lines
- n_lines
; i
; --i
)
720 while (*cp
++ != '\n')
722 i
= cp
- tmp
->buffer
;
726 XWRITE (STDOUT_FILENO
, &tmp
->buffer
[i
], tmp
->nbytes
- i
);
728 for (tmp
= tmp
->next
; tmp
; tmp
= tmp
->next
)
729 XWRITE (STDOUT_FILENO
, tmp
->buffer
, tmp
->nbytes
);
735 free ((char *) first
);
741 /* Print the last N_BYTES characters from the end of pipe FD.
742 This is a stripped down version of pipe_lines.
743 Return 0 if successful, 1 if an error occurred. */
746 pipe_bytes (filename
, fd
, n_bytes
)
747 const char *filename
;
755 struct charbuffer
*next
;
757 typedef struct charbuffer CBUFFER
;
758 CBUFFER
*first
, *last
, *tmp
;
759 int i
; /* Index into buffers. */
760 int total_bytes
= 0; /* Total characters in all buffers. */
763 first
= last
= (CBUFFER
*) xmalloc (sizeof (CBUFFER
));
766 tmp
= (CBUFFER
*) xmalloc (sizeof (CBUFFER
));
768 /* Input is always read into a fresh buffer. */
769 while ((tmp
->nbytes
= safe_read (fd
, tmp
->buffer
, BUFSIZ
)) > 0)
773 total_bytes
+= tmp
->nbytes
;
774 /* If there is enough room in the last buffer read, just append the new
775 one to it. This is because when reading from a pipe, `nbytes' can
776 often be very small. */
777 if (tmp
->nbytes
+ last
->nbytes
< BUFSIZ
)
779 memcpy (&last
->buffer
[last
->nbytes
], tmp
->buffer
, tmp
->nbytes
);
780 last
->nbytes
+= tmp
->nbytes
;
784 /* If there's not enough room, link the new buffer onto the end of
785 the list, then either free up the oldest buffer for the next
786 read if that would leave enough characters, or else malloc a new
787 one. Some compaction mechanism is possible but probably not
789 last
= last
->next
= tmp
;
790 if (total_bytes
- first
->nbytes
> n_bytes
)
793 total_bytes
-= first
->nbytes
;
798 tmp
= (CBUFFER
*) xmalloc (sizeof (CBUFFER
));
802 if (tmp
->nbytes
== -1)
804 error (0, errno
, "%s", filename
);
812 /* Run through the list, printing characters. First, skip over unneeded
814 for (tmp
= first
; total_bytes
- tmp
->nbytes
> n_bytes
; tmp
= tmp
->next
)
815 total_bytes
-= tmp
->nbytes
;
817 /* Find the correct beginning, then print the rest of the file.
818 We made sure that `total_bytes' - `n_bytes' <= `tmp->nbytes'. */
819 if (total_bytes
> n_bytes
)
820 i
= total_bytes
- n_bytes
;
823 XWRITE (STDOUT_FILENO
, &tmp
->buffer
[i
], tmp
->nbytes
- i
);
825 for (tmp
= tmp
->next
; tmp
; tmp
= tmp
->next
)
826 XWRITE (STDOUT_FILENO
, tmp
->buffer
, tmp
->nbytes
);
832 free ((char *) first
);
838 /* Skip N_BYTES characters from the start of pipe FD, and print
839 any extra characters that were read beyond that.
840 Return 1 on error, 0 if ok. */
843 start_bytes (filename
, fd
, n_bytes
)
844 const char *filename
;
851 while (n_bytes
> 0 && (bytes_read
= safe_read (fd
, buffer
, BUFSIZ
)) > 0)
852 n_bytes
-= bytes_read
;
853 if (bytes_read
== -1)
855 error (0, errno
, "%s", filename
);
858 else if (n_bytes
< 0)
859 XWRITE (STDOUT_FILENO
, &buffer
[bytes_read
+ n_bytes
], -n_bytes
);
863 /* Skip N_LINES lines at the start of file or pipe FD, and print
864 any extra characters that were read beyond that.
865 Return 1 on error, 0 if ok. */
868 start_lines (filename
, fd
, n_lines
)
869 const char *filename
;
875 int bytes_to_skip
= 0;
877 while (n_lines
&& (bytes_read
= safe_read (fd
, buffer
, BUFSIZ
)) > 0)
880 while (bytes_to_skip
< bytes_read
)
881 if (buffer
[bytes_to_skip
++] == '\n' && --n_lines
== 0)
884 if (bytes_read
== -1)
886 error (0, errno
, "%s", filename
);
889 else if (bytes_to_skip
< bytes_read
)
891 XWRITE (STDOUT_FILENO
, &buffer
[bytes_to_skip
],
892 bytes_read
- bytes_to_skip
);
897 /* Display file FILENAME from the current position in FD to the end.
898 If `forever' is nonzero, keep reading from the end of the file
899 until killed. Return the number of bytes read from the file. */
902 dump_remainder (filename
, fd
)
903 const char *filename
;
912 while ((bytes_read
= safe_read (fd
, buffer
, BUFSIZ
)) > 0)
914 XWRITE (STDOUT_FILENO
, buffer
, bytes_read
);
917 if (bytes_read
== -1)
918 error (1, errno
, "%s", filename
);
928 /* Tail NFILES (>1) files forever until killed. The file names are in
929 NAMES. The open file descriptors are in `file_descs', and the size
930 at which we stopped tailing them is in `file_sizes'. We loop over
931 each of them, doing an fstat to see if they have changed size. If
932 none of them have changed size in one iteration, we sleep for a
933 second and try again. We do this until the user interrupts us. */
936 tail_forever (names
, nfiles
)
950 for (i
= 0; i
< nfiles
; i
++)
954 if (file_descs
[i
] < 0)
956 if (fstat (file_descs
[i
], &stats
) < 0)
958 error (0, errno
, "%s", names
[i
]);
962 if (stats
.st_size
== file_sizes
[i
])
965 /* This file has changed size. Print out what we can, and
966 then keep looping. */
970 if (stats
.st_size
< file_sizes
[i
])
972 write_header (names
[i
], "file truncated");
974 lseek (file_descs
[i
], stats
.st_size
, SEEK_SET
);
975 file_sizes
[i
] = stats
.st_size
;
982 write_header (names
[i
], NULL
);
985 file_sizes
[i
] += dump_remainder (names
[i
], file_descs
[i
]);
988 /* If none of the files changed size, sleep. */
999 fprintf (stderr
, "Try `%s --help' for more information.\n",
1004 Usage: %s [OPTION]... [FILE]...\n\
1008 Print last 10 lines of each FILE to standard output.\n\
1009 With more than one FILE, precede each with a header giving the file name.\n\
1010 With no FILE, or when FILE is -, read standard input.\n\
1012 -c, --bytes=N output the last N bytes\n\
1013 -f, --follow output appended data as the file grows\n\
1014 -n, --lines=N output the last N lines, instead of last 10\n\
1015 -q, --quiet, --silent never output headers giving file names\n\
1016 -v, --verbose always output headers giving file names\n\
1017 --help display this help and exit\n\
1018 --version output version information and exit\n\
1020 If the first character of N (the number of bytes or lines) is a `+',\n\
1021 print beginning with the Nth item from the start of each file, otherwise,\n\
1022 print the last N items in the file. N may have a multiplier suffix:\n\
1023 b for 512, k for 1024, m for 1048576 (1 Meg). A first OPTION of -VALUE\n\
1024 or +VALUE is treated like -n VALUE or -n +VALUE unless VALUE has one of\n\
1025 the [bkm] suffix multipliers, in which case it is treated like -c VALUE\n\