1 /* tee - duplicate standard input */
3 /* See Makefile for compilation details. */
13 #if defined (HAVE_UNISTD_H)
24 #include "bashgetopt.h"
30 typedef struct flist {
36 static FLIST *tee_flist;
38 #define TEE_BUFSIZE 8192
40 extern int interrupt_immediately;
42 extern char *strerror ();
47 int opt, append, nointr, rval, fd, fflags;
54 reset_internal_getopt ();
56 tee_flist = (FLIST *)NULL;
57 while ((opt = internal_getopt (list, "ai")) != -1)
75 interrupt_immediately++;
77 buf = xmalloc (TEE_BUFSIZE);
79 /* Initialize output file list. */
80 fl = tee_flist = (FLIST *)xmalloc (sizeof(FLIST));
82 tee_flist->fname = "stdout";
83 tee_flist->next = (FLIST *)NULL;
85 /* Add file arguments to list of output files. */
86 fflags = append ? O_WRONLY|O_CREAT|O_APPEND : O_WRONLY|O_CREAT|O_TRUNC;
87 for (rval = EXECUTION_SUCCESS; list; list = list->next)
89 fd = open (list->word->word, fflags, 0666);
92 builtin_error ("%s: cannot open: %s", list->word->word, strerror (errno));
93 rval = EXECUTION_FAILURE;
97 fl->next = (FLIST *)xmalloc (sizeof(FLIST));
99 fl->next->fname = list->word->word;
101 fl->next = (FLIST *)NULL;
105 while ((nr = read(0, buf, TEE_BUFSIZE)) > 0)
106 for (fl = tee_flist; fl; fl = fl->next)
112 if ((nw = write (fl->fd, bp, n)) == -1)
114 builtin_error ("%s: write error: %s", fl->fname, strerror (errno));
115 rval = EXECUTION_FAILURE;
123 builtin_error ("read error: %s", strerror (errno));
125 /* Deallocate resources -- this is a builtin command. */
126 tee_flist = tee_flist->next; /* skip bogus close of stdout */
130 if (close (fl->fd) < 0)
132 builtin_error ("%s: close_error: %s", fl->fname, strerror (errno));
133 rval = EXECUTION_FAILURE;
135 tee_flist = tee_flist->next;
143 "Copy standard input to standard output, making a copy in each",
144 "filename argument. If the `-a' option is gived, the specified",
145 "files are appended to, otherwise they are overwritten. If the",
146 "`-i' option is supplied, tee ignores interrupts.",
150 struct builtin tee_struct = {
151 "tee", /* builtin name */
152 tee_builtin, /* function implementing the builtin */
153 BUILTIN_ENABLED, /* initial flags for builtin */
154 tee_doc, /* array of long documentation strings. */
155 "tee [-ai] [file ...]", /* usage synopsis; becomes short_doc */
156 0 /* reserved for internal use */