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>
57 /* Disable assertions. Some systems have broken assert macros. */
60 #define XWRITE(fd, buffer, n_bytes) \
64 assert ((n_bytes) >= 0); \
65 if (n_bytes > 0 && fwrite ((buffer), 1, (n_bytes), stdout) == 0) \
66 error (1, errno, _("write error")); \
70 /* Number of items to tail. */
71 #define DEFAULT_N_LINES 10
73 /* Size of atomic reads. */
75 #define BUFSIZ (512 * 8)
78 /* If nonzero, interpret the numeric argument as the number of lines.
79 Otherwise, interpret it as the number of bytes. */
80 static int count_lines;
82 /* If nonzero, read from the end of one file until killed. */
85 /* If nonzero, read from the end of multiple files until killed. */
86 static int forever_multiple;
88 /* Array of file descriptors if forever_multiple is 1. */
89 static int *file_descs;
91 /* Array of file sizes if forever_multiple is 1. */
92 static off_t *file_sizes;
94 /* If nonzero, count from start of file instead of end. */
95 static int from_start;
97 /* If nonzero, print filename headers. */
98 static int print_headers;
100 /* When to print the filename banners. */
103 multiple_files, always, never
109 /* The name this program was run with. */
112 /* Nonzero if we have ever read standard input. */
113 static int have_read_stdin;
115 /* If nonzero, display usage information and exit. */
116 static int show_help;
118 /* If nonzero, print the version on standard output then exit. */
119 static int show_version;
121 static struct option const long_options[] =
123 {"bytes", required_argument, NULL, 'c'},
124 {"follow", no_argument, NULL, 'f'},
125 {"lines", required_argument, NULL, 'n'},
126 {"quiet", no_argument, NULL, 'q'},
127 {"silent", no_argument, NULL, 'q'},
128 {"verbose", no_argument, NULL, 'v'},
129 {"help", no_argument, &show_help, 1},
130 {"version", no_argument, &show_version, 1},
138 fprintf (stderr, _("Try `%s --help' for more information.\n"),
143 Usage: %s [OPTION]... [FILE]...\n\
147 Print last 10 lines of each FILE to standard output.\n\
148 With more than one FILE, precede each with a header giving the file name.\n\
149 With no FILE, or when FILE is -, read standard input.\n\
151 -c, --bytes=N output the last N bytes\n\
152 -f, --follow output appended data as the file grows\n\
153 -n, --lines=N output the last N lines, instead of last 10\n\
154 -q, --quiet, --silent never output headers giving file names\n\
155 -v, --verbose always output headers giving file names\n\
156 --help display this help and exit\n\
157 --version output version information and exit\n\
159 If the first character of N (the number of bytes or lines) is a `+',\n\
160 print beginning with the Nth item from the start of each file, otherwise,\n\
161 print the last N items in the file. N may have a multiplier suffix:\n\
162 b for 512, k for 1024, m for 1048576 (1 Meg). A first OPTION of -VALUE\n\
163 or +VALUE is treated like -n VALUE or -n +VALUE unless VALUE has one of\n\
164 the [bkm] suffix multipliers, in which case it is treated like -c VALUE\n\
172 write_header (const char *filename, const char *comment)
174 static int first_file = 1;
176 printf ("%s==> %s%s%s <==\n", (first_file ? "" : "\n"), filename,
177 (comment ? ": " : ""),
178 (comment ? comment : ""));
182 /* Print the last N_LINES lines from the end of file FD.
183 Go backward through the file, reading `BUFSIZ' bytes at a time (except
184 probably the first), until we hit the start of the file or have
185 read NUMBER newlines.
186 POS starts out as the length of the file (the offset of the last
187 byte of the file + 1).
188 Return 0 if successful, 1 if an error occurred. */
191 file_lines (const char *filename, int fd, long int n_lines, off_t pos)
195 int i; /* Index into `buffer' for scanning. */
200 /* Set `bytes_read' to the size of the last, probably partial, buffer;
201 0 < `bytes_read' <= `BUFSIZ'. */
202 bytes_read = pos % BUFSIZ;
205 /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all
206 reads will be on block boundaries, which might increase efficiency. */
208 lseek (fd, pos, SEEK_SET);
209 bytes_read = safe_read (fd, buffer, bytes_read);
210 if (bytes_read == -1)
212 error (0, errno, "%s", filename);
216 /* Count the incomplete line on files that don't end with a newline. */
217 if (bytes_read && buffer[bytes_read - 1] != '\n')
222 /* Scan backward, counting the newlines in this bufferfull. */
223 for (i = bytes_read - 1; i >= 0; i--)
225 /* Have we counted the requested number of newlines yet? */
226 if (buffer[i] == '\n' && n_lines-- == 0)
228 /* If this newline wasn't the last character in the buffer,
229 print the text after it. */
230 if (i != bytes_read - 1)
231 XWRITE (STDOUT_FILENO, &buffer[i + 1], bytes_read - (i + 1));
235 /* Not enough newlines in that bufferfull. */
238 /* Not enough lines in the file; print the entire file. */
239 lseek (fd, (off_t) 0, SEEK_SET);
243 lseek (fd, pos, SEEK_SET);
245 while ((bytes_read = safe_read (fd, buffer, BUFSIZ)) > 0);
246 if (bytes_read == -1)
248 error (0, errno, "%s", filename);
254 /* Print the last N_LINES lines from the end of the standard input,
255 open for reading as pipe FD.
256 Buffer the text as a linked list of LBUFFERs, adding them as needed.
257 Return 0 if successful, 1 if an error occured. */
260 pipe_lines (const char *filename, int fd, long int n_lines)
266 struct linebuffer *next;
268 typedef struct linebuffer LBUFFER;
269 LBUFFER *first, *last, *tmp;
270 int i; /* Index into buffers. */
271 int total_lines = 0; /* Total number of newlines in all buffers. */
274 first = last = (LBUFFER *) xmalloc (sizeof (LBUFFER));
275 first->nbytes = first->nlines = 0;
277 tmp = (LBUFFER *) xmalloc (sizeof (LBUFFER));
279 /* Input is always read into a fresh buffer. */
280 while ((tmp->nbytes = safe_read (fd, tmp->buffer, BUFSIZ)) > 0)
285 /* Count the number of newlines just read. */
286 for (i = 0; i < tmp->nbytes; i++)
287 if (tmp->buffer[i] == '\n')
289 total_lines += tmp->nlines;
291 /* If there is enough room in the last buffer read, just append the new
292 one to it. This is because when reading from a pipe, `nbytes' can
293 often be very small. */
294 if (tmp->nbytes + last->nbytes < BUFSIZ)
296 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
297 last->nbytes += tmp->nbytes;
298 last->nlines += tmp->nlines;
302 /* If there's not enough room, link the new buffer onto the end of
303 the list, then either free up the oldest buffer for the next
304 read if that would leave enough lines, or else malloc a new one.
305 Some compaction mechanism is possible but probably not
307 last = last->next = tmp;
308 if (total_lines - first->nlines > n_lines)
311 total_lines -= first->nlines;
315 tmp = (LBUFFER *) xmalloc (sizeof (LBUFFER));
318 if (tmp->nbytes == -1)
320 error (0, errno, "%s", filename);
328 /* This prevents a core dump when the pipe contains no newlines. */
332 /* Count the incomplete line on files that don't end with a newline. */
333 if (last->buffer[last->nbytes - 1] != '\n')
339 /* Run through the list, printing lines. First, skip over unneeded
341 for (tmp = first; total_lines - tmp->nlines > n_lines; tmp = tmp->next)
342 total_lines -= tmp->nlines;
344 /* Find the correct beginning, then print the rest of the file. */
345 if (total_lines > n_lines)
349 /* Skip `total_lines' - `n_lines' newlines. We made sure that
350 `total_lines' - `n_lines' <= `tmp->nlines'. */
352 for (i = total_lines - n_lines; i; --i)
353 while (*cp++ != '\n')
355 i = cp - tmp->buffer;
359 XWRITE (STDOUT_FILENO, &tmp->buffer[i], tmp->nbytes - i);
361 for (tmp = tmp->next; tmp; tmp = tmp->next)
362 XWRITE (STDOUT_FILENO, tmp->buffer, tmp->nbytes);
368 free ((char *) first);
374 /* Print the last N_BYTES characters from the end of pipe FD.
375 This is a stripped down version of pipe_lines.
376 Return 0 if successful, 1 if an error occurred. */
379 pipe_bytes (const char *filename, int fd, off_t n_bytes)
385 struct charbuffer *next;
387 typedef struct charbuffer CBUFFER;
388 CBUFFER *first, *last, *tmp;
389 int i; /* Index into buffers. */
390 int total_bytes = 0; /* Total characters in all buffers. */
393 first = last = (CBUFFER *) xmalloc (sizeof (CBUFFER));
396 tmp = (CBUFFER *) xmalloc (sizeof (CBUFFER));
398 /* Input is always read into a fresh buffer. */
399 while ((tmp->nbytes = safe_read (fd, tmp->buffer, BUFSIZ)) > 0)
403 total_bytes += tmp->nbytes;
404 /* If there is enough room in the last buffer read, just append the new
405 one to it. This is because when reading from a pipe, `nbytes' can
406 often be very small. */
407 if (tmp->nbytes + last->nbytes < BUFSIZ)
409 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
410 last->nbytes += tmp->nbytes;
414 /* If there's not enough room, link the new buffer onto the end of
415 the list, then either free up the oldest buffer for the next
416 read if that would leave enough characters, or else malloc a new
417 one. Some compaction mechanism is possible but probably not
419 last = last->next = tmp;
420 if (total_bytes - first->nbytes > n_bytes)
423 total_bytes -= first->nbytes;
428 tmp = (CBUFFER *) xmalloc (sizeof (CBUFFER));
432 if (tmp->nbytes == -1)
434 error (0, errno, "%s", filename);
442 /* Run through the list, printing characters. First, skip over unneeded
444 for (tmp = first; total_bytes - tmp->nbytes > n_bytes; tmp = tmp->next)
445 total_bytes -= tmp->nbytes;
447 /* Find the correct beginning, then print the rest of the file.
448 We made sure that `total_bytes' - `n_bytes' <= `tmp->nbytes'. */
449 if (total_bytes > n_bytes)
450 i = total_bytes - n_bytes;
453 XWRITE (STDOUT_FILENO, &tmp->buffer[i], tmp->nbytes - i);
455 for (tmp = tmp->next; tmp; tmp = tmp->next)
456 XWRITE (STDOUT_FILENO, tmp->buffer, tmp->nbytes);
462 free ((char *) first);
468 /* Skip N_BYTES characters from the start of pipe FD, and print
469 any extra characters that were read beyond that.
470 Return 1 on error, 0 if ok. */
473 start_bytes (const char *filename, int fd, off_t n_bytes)
478 while (n_bytes > 0 && (bytes_read = safe_read (fd, buffer, BUFSIZ)) > 0)
479 n_bytes -= bytes_read;
480 if (bytes_read == -1)
482 error (0, errno, "%s", filename);
485 else if (n_bytes < 0)
486 XWRITE (STDOUT_FILENO, &buffer[bytes_read + n_bytes], -n_bytes);
490 /* Skip N_LINES lines at the start of file or pipe FD, and print
491 any extra characters that were read beyond that.
492 Return 1 on error, 0 if ok. */
495 start_lines (const char *filename, int fd, long int n_lines)
499 int bytes_to_skip = 0;
501 while (n_lines && (bytes_read = safe_read (fd, buffer, BUFSIZ)) > 0)
504 while (bytes_to_skip < bytes_read)
505 if (buffer[bytes_to_skip++] == '\n' && --n_lines == 0)
508 if (bytes_read == -1)
510 error (0, errno, "%s", filename);
513 else if (bytes_to_skip < bytes_read)
515 XWRITE (STDOUT_FILENO, &buffer[bytes_to_skip],
516 bytes_read - bytes_to_skip);
521 /* Display file FILENAME from the current position in FD to the end.
522 If `forever' is nonzero, keep reading from the end of the file
523 until killed. Return the number of bytes read from the file. */
526 dump_remainder (const char *filename, int fd)
534 while ((bytes_read = safe_read (fd, buffer, BUFSIZ)) > 0)
536 XWRITE (STDOUT_FILENO, buffer, bytes_read);
539 if (bytes_read == -1)
540 error (1, errno, "%s", filename);
549 if (forever_multiple)
556 /* Tail NFILES (>1) files forever until killed. The file names are in
557 NAMES. The open file descriptors are in `file_descs', and the size
558 at which we stopped tailing them is in `file_sizes'. We loop over
559 each of them, doing an fstat to see if they have changed size. If
560 none of them have changed size in one iteration, we sleep for a
561 second and try again. We do this until the user interrupts us. */
564 tail_forever (char **names, int nfiles)
576 for (i = 0; i < nfiles; i++)
580 if (file_descs[i] < 0)
582 if (fstat (file_descs[i], &stats) < 0)
584 error (0, errno, "%s", names[i]);
588 if (stats.st_size == file_sizes[i])
591 /* This file has changed size. Print out what we can, and
592 then keep looping. */
596 if (stats.st_size < file_sizes[i])
598 write_header (names[i], _("file truncated"));
600 lseek (file_descs[i], stats.st_size, SEEK_SET);
601 file_sizes[i] = stats.st_size;
608 write_header (names[i], NULL);
611 file_sizes[i] += dump_remainder (names[i], file_descs[i]);
614 /* If none of the files changed size, sleep. */
620 /* Output the last N_BYTES bytes of file FILENAME open for reading in FD.
621 Return 0 if successful, 1 if an error occurred. */
624 tail_bytes (const char *filename, int fd, off_t n_bytes)
628 /* FIXME: resolve this like in dd.c. */
629 /* Use fstat instead of checking for errno == ESPIPE because
630 lseek doesn't work on some special files but doesn't return an
632 if (fstat (fd, &stats))
634 error (0, errno, "%s", filename);
640 if (S_ISREG (stats.st_mode))
641 lseek (fd, n_bytes, SEEK_CUR);
642 else if (start_bytes (filename, fd, n_bytes))
644 dump_remainder (filename, fd);
648 if (S_ISREG (stats.st_mode))
650 off_t current_pos, end_pos;
651 size_t bytes_remaining;
653 if ((current_pos = lseek (fd, (off_t) 0, SEEK_CUR)) != -1
654 && (end_pos = lseek (fd, (off_t) 0, SEEK_END)) != -1)
657 /* Be careful here. The current position may actually be
658 beyond the end of the file. */
659 bytes_remaining = (diff = end_pos - current_pos) < 0 ? 0 : diff;
663 error (0, errno, "%s", filename);
667 if (bytes_remaining <= n_bytes)
669 /* From the current position to end of file, there are no
670 more bytes than have been requested. So reposition the
671 file pointer to the incoming current position and print
672 everything after that. */
673 lseek (fd, current_pos, SEEK_SET);
677 /* There are more bytes remaining than were requested.
679 lseek (fd, -n_bytes, SEEK_END);
681 dump_remainder (filename, fd);
684 return pipe_bytes (filename, fd, n_bytes);
689 /* Output the last N_LINES lines of file FILENAME open for reading in FD.
690 Return 0 if successful, 1 if an error occurred. */
693 tail_lines (const char *filename, int fd, long int n_lines)
698 if (fstat (fd, &stats))
700 error (0, errno, "%s", filename);
706 if (start_lines (filename, fd, n_lines))
708 dump_remainder (filename, fd);
712 /* Use file_lines only if FD refers to a regular file with
713 its file pointer positioned at beginning of file. */
714 /* FIXME: adding the lseek conjunct is a kludge.
715 Once there's a reasonable test suite, fix the true culprit:
716 file_lines. file_lines shouldn't presume that the input
717 file pointer is initially positioned to beginning of file. */
718 if (S_ISREG (stats.st_mode)
719 && lseek (fd, (off_t) 0, SEEK_CUR) == (off_t) 0)
721 length = lseek (fd, (off_t) 0, SEEK_END);
722 if (length != 0 && file_lines (filename, fd, n_lines, length))
724 dump_remainder (filename, fd);
727 return pipe_lines (filename, fd, n_lines);
732 /* Display the last N_UNITS units of file FILENAME, open for reading
734 Return 0 if successful, 1 if an error occurred. */
737 tail (const char *filename, int fd, off_t n_units)
740 return tail_lines (filename, fd, (long) n_units);
742 return tail_bytes (filename, fd, n_units);
745 /* Display the last N_UNITS units of file FILENAME.
746 "-" for FILENAME means the standard input.
747 FILENUM is this file's index in the list of files the user gave.
748 Return 0 if successful, 1 if an error occurred. */
751 tail_file (const char *filename, off_t n_units, int filenum)
756 if (!strcmp (filename, "-"))
759 filename = _("standard input");
761 write_header (filename, NULL);
762 errors = tail (filename, 0, n_units);
763 if (forever_multiple)
765 if (fstat (0, &stats) < 0)
767 error (0, errno, _("standard input"));
770 else if (!S_ISREG (stats.st_mode))
773 _("standard input: cannot follow end of non-regular file"));
777 file_descs[filenum] = -1;
780 file_descs[filenum] = 0;
781 file_sizes[filenum] = stats.st_size;
787 /* Not standard input. */
788 fd = open (filename, O_RDONLY);
791 if (forever_multiple)
792 file_descs[filenum] = -1;
793 error (0, errno, "%s", filename);
799 write_header (filename, NULL);
800 errors = tail (filename, fd, n_units);
801 if (forever_multiple)
803 if (fstat (fd, &stats) < 0)
805 error (0, errno, "%s", filename);
808 else if (!S_ISREG (stats.st_mode))
810 error (0, 0, _("%s: cannot follow end of non-regular file"),
817 file_descs[filenum] = -1;
821 file_descs[filenum] = fd;
822 file_sizes[filenum] = stats.st_size;
829 error (0, errno, "%s", filename);
840 main (int argc, char **argv)
842 enum header_mode header_mode = multiple_files;
844 /* If from_start, the number of items to skip before printing; otherwise,
845 the number of items at the end of the file to print. Initially, -1
846 means the value has not been set. */
849 int c; /* Option character. */
850 int fileind; /* Index in ARGV of first file name. */
852 program_name = argv[0];
853 setlocale (LC_ALL, "");
854 bindtextdomain (PACKAGE, LOCALEDIR);
855 textdomain (PACKAGE);
859 forever = forever_multiple = from_start = print_headers = 0;
862 && ((argv[1][0] == '-' && ISDIGIT (argv[1][1]))
863 || (argv[1][0] == '+' && (ISDIGIT (argv[1][1]) || argv[1][1] == 0))))
865 /* Old option syntax: a dash or plus, one or more digits (zero digits
866 are acceptable with a plus), and one or more option letters. */
867 if (argv[1][0] == '+')
869 if (argv[1][1] != '\0')
874 s_err = xstrtol (++argv[1], &p, 0, &tmp_long, "bkm");
876 if (s_err == LONGINT_OVERFLOW)
878 STRTOL_FATAL_ERROR (argv[1], _("argument"), s_err);
880 /* Parse any appended option letters. */
886 /* Interpret N_UNITS as # of bytes. */
903 header_mode = always;
907 error (0, 0, _("unrecognized option `-%c'"), *p);
913 /* Make the options we just parsed invisible to getopt. */
919 while ((c = getopt_long (argc, argv, "c:n:fqv", long_options, (int *) 0))
941 s_err = xstrtol (optarg, NULL, 0, &tmp_long, "bkm");
943 tmp_long = -tmp_long;
945 if (s_err != LONGINT_OK)
947 STRTOL_FATAL_ERROR (optarg, (c == 'n'
948 ? _("number of lines")
949 : _("number of bytes")), s_err);
962 header_mode = always;
972 printf ("tail - %s\n", PACKAGE_VERSION);
980 n_units = DEFAULT_N_LINES;
982 /* To start printing with item N_UNITS from the start of the file, skip
983 N_UNITS - 1 items. `tail +0' is actually meaningless, but for Unix
984 compatibility it's treated the same as `tail +1'. */
993 if (optind < argc - 1 && forever)
995 forever_multiple = 1;
997 file_descs = (int *) xmalloc ((argc - optind) * sizeof (int));
998 file_sizes = (off_t *) xmalloc ((argc - optind) * sizeof (off_t));
1001 if (header_mode == always
1002 || (header_mode == multiple_files && optind < argc - 1))
1006 exit_status |= tail_file ("-", n_units, 0);
1008 for (; optind < argc; ++optind)
1009 exit_status |= tail_file (argv[optind], n_units, optind - fileind);
1011 if (forever_multiple)
1012 tail_forever (argv + fileind, argc - fileind);
1014 if (have_read_stdin && close (0) < 0)
1015 error (1, errno, "-");
1016 if (fclose (stdout) == EOF)
1017 error (1, errno, _("write error"));