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., 675 Mass Ave, Cambridge, MA 02139, 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))
230 int allow_bkm_suffix;
240 allow_bkm_suffix = 1;
245 allow_bkm_suffix = 0;
252 s_err = xstrtol (optarg, NULL, 0, &tmp_long, "bkm");
254 tmp_long = -tmp_long;
256 if (s_err != LONGINT_OK)
258 STRTOL_FATAL_ERROR (optarg, (c == 'n'
260 : "number of bytes"), s_err);
273 header_mode = always;
283 printf ("tail - %s\n", version_string);
291 n_units = DEFAULT_N_LINES;
293 /* To start printing with item N_UNITS from the start of the file, skip
294 N_UNITS - 1 items. `tail +0' is actually meaningless, but for Unix
295 compatibility it's treated the same as `tail +1'. */
304 if (optind < argc - 1 && forever)
306 forever_multiple = 1;
308 file_descs = (int *) xmalloc ((argc - optind) * sizeof (int));
309 file_sizes = (off_t *) xmalloc ((argc - optind) * sizeof (off_t));
312 if (header_mode == always
313 || (header_mode == multiple_files && optind < argc - 1))
317 exit_status |= tail_file ("-", n_units, 0);
319 for (; optind < argc; ++optind)
320 exit_status |= tail_file (argv[optind], n_units, optind - fileind);
322 if (forever_multiple)
323 tail_forever (argv + fileind, argc - fileind);
325 if (have_read_stdin && close (0) < 0)
326 error (1, errno, "-");
327 if (fclose (stdout) == EOF)
328 error (1, errno, "write error");
332 /* Display the last N_UNITS units of file FILENAME.
333 "-" for FILENAME means the standard input.
334 FILENUM is this file's index in the list of files the user gave.
335 Return 0 if successful, 1 if an error occurred. */
338 tail_file (filename, n_units, filenum)
339 const char *filename;
346 if (!strcmp (filename, "-"))
349 filename = "standard input";
351 write_header (filename, NULL);
352 errors = tail (filename, 0, n_units);
353 if (forever_multiple)
355 if (fstat (0, &stats) < 0)
357 error (0, errno, "standard input");
360 else if (!S_ISREG (stats.st_mode))
363 "standard input: cannot follow end of non-regular file");
367 file_descs[filenum] = -1;
370 file_descs[filenum] = 0;
371 file_sizes[filenum] = stats.st_size;
377 /* Not standard input. */
378 fd = open (filename, O_RDONLY);
381 if (forever_multiple)
382 file_descs[filenum] = -1;
383 error (0, errno, "%s", filename);
389 write_header (filename, NULL);
390 errors = tail (filename, fd, n_units);
391 if (forever_multiple)
393 if (fstat (fd, &stats) < 0)
395 error (0, errno, "%s", filename);
398 else if (!S_ISREG (stats.st_mode))
400 error (0, 0, "%s: cannot follow end of non-regular file",
407 file_descs[filenum] = -1;
411 file_descs[filenum] = fd;
412 file_sizes[filenum] = stats.st_size;
419 error (0, errno, "%s", filename);
430 write_header (filename, comment)
431 const char *filename;
434 static int first_file = 1;
436 printf ("%s==> %s%s%s <==\n", (first_file ? "" : "\n"), filename,
437 (comment ? ": " : ""),
438 (comment ? comment : ""));
442 /* Display the last N_UNITS units of file FILENAME, open for reading
444 Return 0 if successful, 1 if an error occurred. */
447 tail (filename, fd, n_units)
448 const char *filename;
453 return tail_lines (filename, fd, n_units);
455 return tail_bytes (filename, fd, n_units);
458 /* Output the last N_BYTES bytes of file FILENAME open for reading in FD.
459 Return 0 if successful, 1 if an error occurred. */
462 tail_bytes (filename, fd, n_bytes)
463 const char *filename;
469 /* FIXME: resolve this like in dd.c. */
470 /* Use fstat instead of checking for errno == ESPIPE because
471 lseek doesn't work on some special files but doesn't return an
473 if (fstat (fd, &stats))
475 error (0, errno, "%s", filename);
481 if (S_ISREG (stats.st_mode))
482 lseek (fd, n_bytes, SEEK_SET);
483 else if (start_bytes (filename, fd, n_bytes))
485 dump_remainder (filename, fd);
489 if (S_ISREG (stats.st_mode))
491 if (lseek (fd, (off_t) 0, SEEK_END) <= n_bytes)
492 /* The file is shorter than we want, or just the right size, so
493 print the whole file. */
494 lseek (fd, (off_t) 0, SEEK_SET);
496 /* The file is longer than we want, so go back. */
497 lseek (fd, -n_bytes, SEEK_END);
498 dump_remainder (filename, fd);
501 return pipe_bytes (filename, fd, n_bytes);
506 /* Output the last N_LINES lines of file FILENAME open for reading in FD.
507 Return 0 if successful, 1 if an error occurred. */
510 tail_lines (filename, fd, n_lines)
511 const char *filename;
518 if (fstat (fd, &stats))
520 error (0, errno, "%s", filename);
526 if (start_lines (filename, fd, n_lines))
528 dump_remainder (filename, fd);
532 if (S_ISREG (stats.st_mode))
534 length = lseek (fd, (off_t) 0, SEEK_END);
535 if (length != 0 && file_lines (filename, fd, n_lines, length))
537 dump_remainder (filename, fd);
540 return pipe_lines (filename, fd, n_lines);
545 /* Print the last N_LINES lines from the end of file FD.
546 Go backward through the file, reading `BUFSIZ' bytes at a time (except
547 probably the first), until we hit the start of the file or have
548 read NUMBER newlines.
549 POS starts out as the length of the file (the offset of the last
550 byte of the file + 1).
551 Return 0 if successful, 1 if an error occurred. */
554 file_lines (filename, fd, n_lines, pos)
555 const char *filename;
562 int i; /* Index into `buffer' for scanning. */
567 /* Set `bytes_read' to the size of the last, probably partial, buffer;
568 0 < `bytes_read' <= `BUFSIZ'. */
569 bytes_read = pos % BUFSIZ;
572 /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all
573 reads will be on block boundaries, which might increase efficiency. */
575 lseek (fd, pos, SEEK_SET);
576 bytes_read = safe_read (fd, buffer, bytes_read);
577 if (bytes_read == -1)
579 error (0, errno, "%s", filename);
583 /* Count the incomplete line on files that don't end with a newline. */
584 if (bytes_read && buffer[bytes_read - 1] != '\n')
589 /* Scan backward, counting the newlines in this bufferfull. */
590 for (i = bytes_read - 1; i >= 0; i--)
592 /* Have we counted the requested number of newlines yet? */
593 if (buffer[i] == '\n' && n_lines-- == 0)
595 /* If this newline wasn't the last character in the buffer,
596 print the text after it. */
597 if (i != bytes_read - 1)
598 XWRITE (STDOUT_FILENO, &buffer[i + 1], bytes_read - (i + 1));
602 /* Not enough newlines in that bufferfull. */
605 /* Not enough lines in the file; print the entire file. */
606 lseek (fd, (off_t) 0, SEEK_SET);
610 lseek (fd, pos, SEEK_SET);
612 while ((bytes_read = safe_read (fd, buffer, BUFSIZ)) > 0);
613 if (bytes_read == -1)
615 error (0, errno, "%s", filename);
621 /* Print the last N_LINES lines from the end of the standard input,
622 open for reading as pipe FD.
623 Buffer the text as a linked list of LBUFFERs, adding them as needed.
624 Return 0 if successful, 1 if an error occured. */
627 pipe_lines (filename, fd, n_lines)
628 const char *filename;
636 struct linebuffer *next;
638 typedef struct linebuffer LBUFFER;
639 LBUFFER *first, *last, *tmp;
640 int i; /* Index into buffers. */
641 int total_lines = 0; /* Total number of newlines in all buffers. */
644 first = last = (LBUFFER *) xmalloc (sizeof (LBUFFER));
645 first->nbytes = first->nlines = 0;
647 tmp = (LBUFFER *) xmalloc (sizeof (LBUFFER));
649 /* Input is always read into a fresh buffer. */
650 while ((tmp->nbytes = safe_read (fd, tmp->buffer, BUFSIZ)) > 0)
655 /* Count the number of newlines just read. */
656 for (i = 0; i < tmp->nbytes; i++)
657 if (tmp->buffer[i] == '\n')
659 total_lines += tmp->nlines;
661 /* If there is enough room in the last buffer read, just append the new
662 one to it. This is because when reading from a pipe, `nbytes' can
663 often be very small. */
664 if (tmp->nbytes + last->nbytes < BUFSIZ)
666 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
667 last->nbytes += tmp->nbytes;
668 last->nlines += tmp->nlines;
672 /* If there's not enough room, link the new buffer onto the end of
673 the list, then either free up the oldest buffer for the next
674 read if that would leave enough lines, or else malloc a new one.
675 Some compaction mechanism is possible but probably not
677 last = last->next = tmp;
678 if (total_lines - first->nlines > n_lines)
681 total_lines -= first->nlines;
685 tmp = (LBUFFER *) xmalloc (sizeof (LBUFFER));
688 if (tmp->nbytes == -1)
690 error (0, errno, "%s", filename);
698 /* This prevents a core dump when the pipe contains no newlines. */
702 /* Count the incomplete line on files that don't end with a newline. */
703 if (last->buffer[last->nbytes - 1] != '\n')
709 /* Run through the list, printing lines. First, skip over unneeded
711 for (tmp = first; total_lines - tmp->nlines > n_lines; tmp = tmp->next)
712 total_lines -= tmp->nlines;
714 /* Find the correct beginning, then print the rest of the file. */
715 if (total_lines > n_lines)
719 /* Skip `total_lines' - `n_lines' newlines. We made sure that
720 `total_lines' - `n_lines' <= `tmp->nlines'. */
722 for (i = total_lines - n_lines; i; --i)
723 while (*cp++ != '\n')
725 i = cp - tmp->buffer;
729 XWRITE (STDOUT_FILENO, &tmp->buffer[i], tmp->nbytes - i);
731 for (tmp = tmp->next; tmp; tmp = tmp->next)
732 XWRITE (STDOUT_FILENO, tmp->buffer, tmp->nbytes);
738 free ((char *) first);
744 /* Print the last N_BYTES characters from the end of pipe FD.
745 This is a stripped down version of pipe_lines.
746 Return 0 if successful, 1 if an error occurred. */
749 pipe_bytes (filename, fd, n_bytes)
750 const char *filename;
758 struct charbuffer *next;
760 typedef struct charbuffer CBUFFER;
761 CBUFFER *first, *last, *tmp;
762 int i; /* Index into buffers. */
763 int total_bytes = 0; /* Total characters in all buffers. */
766 first = last = (CBUFFER *) xmalloc (sizeof (CBUFFER));
769 tmp = (CBUFFER *) xmalloc (sizeof (CBUFFER));
771 /* Input is always read into a fresh buffer. */
772 while ((tmp->nbytes = safe_read (fd, tmp->buffer, BUFSIZ)) > 0)
776 total_bytes += tmp->nbytes;
777 /* If there is enough room in the last buffer read, just append the new
778 one to it. This is because when reading from a pipe, `nbytes' can
779 often be very small. */
780 if (tmp->nbytes + last->nbytes < BUFSIZ)
782 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
783 last->nbytes += tmp->nbytes;
787 /* If there's not enough room, link the new buffer onto the end of
788 the list, then either free up the oldest buffer for the next
789 read if that would leave enough characters, or else malloc a new
790 one. Some compaction mechanism is possible but probably not
792 last = last->next = tmp;
793 if (total_bytes - first->nbytes > n_bytes)
796 total_bytes -= first->nbytes;
801 tmp = (CBUFFER *) xmalloc (sizeof (CBUFFER));
805 if (tmp->nbytes == -1)
807 error (0, errno, "%s", filename);
815 /* Run through the list, printing characters. First, skip over unneeded
817 for (tmp = first; total_bytes - tmp->nbytes > n_bytes; tmp = tmp->next)
818 total_bytes -= tmp->nbytes;
820 /* Find the correct beginning, then print the rest of the file.
821 We made sure that `total_bytes' - `n_bytes' <= `tmp->nbytes'. */
822 if (total_bytes > n_bytes)
823 i = total_bytes - n_bytes;
826 XWRITE (STDOUT_FILENO, &tmp->buffer[i], tmp->nbytes - i);
828 for (tmp = tmp->next; tmp; tmp = tmp->next)
829 XWRITE (STDOUT_FILENO, tmp->buffer, tmp->nbytes);
835 free ((char *) first);
841 /* Skip N_BYTES characters from the start of pipe FD, and print
842 any extra characters that were read beyond that.
843 Return 1 on error, 0 if ok. */
846 start_bytes (filename, fd, n_bytes)
847 const char *filename;
854 while (n_bytes > 0 && (bytes_read = safe_read (fd, buffer, BUFSIZ)) > 0)
855 n_bytes -= bytes_read;
856 if (bytes_read == -1)
858 error (0, errno, "%s", filename);
861 else if (n_bytes < 0)
862 XWRITE (STDOUT_FILENO, &buffer[bytes_read + n_bytes], -n_bytes);
866 /* Skip N_LINES lines at the start of file or pipe FD, and print
867 any extra characters that were read beyond that.
868 Return 1 on error, 0 if ok. */
871 start_lines (filename, fd, n_lines)
872 const char *filename;
878 int bytes_to_skip = 0;
880 while (n_lines && (bytes_read = safe_read (fd, buffer, BUFSIZ)) > 0)
883 while (bytes_to_skip < bytes_read)
884 if (buffer[bytes_to_skip++] == '\n' && --n_lines == 0)
887 if (bytes_read == -1)
889 error (0, errno, "%s", filename);
892 else if (bytes_to_skip < bytes_read)
894 XWRITE (STDOUT_FILENO, &buffer[bytes_to_skip],
895 bytes_read - bytes_to_skip);
900 /* Display file FILENAME from the current position in FD to the end.
901 If `forever' is nonzero, keep reading from the end of the file
902 until killed. Return the number of bytes read from the file. */
905 dump_remainder (filename, fd)
906 const char *filename;
915 while ((bytes_read = safe_read (fd, buffer, BUFSIZ)) > 0)
917 XWRITE (STDOUT_FILENO, buffer, bytes_read);
920 if (bytes_read == -1)
921 error (1, errno, "%s", filename);
931 /* Tail NFILES (>1) files forever until killed. The file names are in
932 NAMES. The open file descriptors are in `file_descs', and the size
933 at which we stopped tailing them is in `file_sizes'. We loop over
934 each of them, doing an fstat to see if they have changed size. If
935 none of them have changed size in one iteration, we sleep for a
936 second and try again. We do this until the user interrupts us. */
939 tail_forever (names, nfiles)
953 for (i = 0; i < nfiles; i++)
957 if (file_descs[i] < 0)
959 if (fstat (file_descs[i], &stats) < 0)
961 error (0, errno, "%s", names[i]);
965 if (stats.st_size == file_sizes[i])
968 /* This file has changed size. Print out what we can, and
969 then keep looping. */
973 if (stats.st_size < file_sizes[i])
975 write_header (names[i], "file truncated");
977 lseek (file_descs[i], stats.st_size, SEEK_SET);
978 file_sizes[i] = stats.st_size;
985 write_header (names[i], NULL);
988 file_sizes[i] += dump_remainder (names[i], file_descs[i]);
991 /* If none of the files changed size, sleep. */
1002 fprintf (stderr, "Try `%s --help' for more information.\n",
1007 Usage: %s [OPTION]... [FILE]...\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\
1026 or -c +VALUE. With no FILE, or when FILE is -, read standard input.\n\