Imported from ../bash-2.05b.tar.gz.
[platform/upstream/bash.git] / builtins / read.def
1 This file is read.def, from which is created read.c.
2 It implements the builtin "read" in Bash.
3
4 Copyright (C) 1987-2002 Free Software Foundation, Inc.
5
6 This file is part of GNU Bash, the Bourne Again SHell.
7
8 Bash is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 2, or (at your option) any later
11 version.
12
13 Bash is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License along
19 with Bash; see the file COPYING.  If not, write to the Free Software
20 Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA.
21
22 $PRODUCES read.c
23
24 $BUILTIN read
25 $FUNCTION read_builtin
26 $SHORT_DOC read [-ers] [-u fd] [-t timeout] [-p prompt] [-a array] [-n nchars] [-d delim] [name ...]
27 One line is read from the standard input, or from file descriptor FD if the
28 -u option is supplied, and the first word is assigned to the first NAME,
29 the second word to the second NAME, and so on, with leftover words assigned
30 to the last NAME.  Only the characters found in $IFS are recognized as word
31 delimiters.  If no NAMEs are supplied, the line read is stored in the REPLY
32 variable.  If the -r option is given, this signifies `raw' input, and
33 backslash escaping is disabled.  The -d option causes read to continue
34 until the first character of DELIM is read, rather than newline.  If the -p
35 option is supplied, the string PROMPT is output without a trailing newline
36 before attempting to read.  If -a is supplied, the words read are assigned
37 to sequential indices of ARRAY, starting at zero.  If -e is supplied and
38 the shell is interactive, readline is used to obtain the line.  If -n is
39 supplied with a non-zero NCHARS argument, read returns after NCHARS
40 characters have been read.  The -s option causes input coming from a
41 terminal to not be echoed.
42
43 The -t option causes read to time out and return failure if a complete line
44 of input is not read within TIMEOUT seconds.  If the TMOUT variable is set,
45 its value is the default timeout.  The return code is zero, unless end-of-file
46 is encountered, read times out, or an invalid file descriptor is supplied as
47 the argument to -u.
48 $END
49
50 #include <config.h>
51
52 #include "bashtypes.h"
53 #include "posixstat.h"
54
55 #include <stdio.h>
56
57 #if defined (HAVE_UNISTD_H)
58 #  include <unistd.h>
59 #endif
60
61 #include <signal.h>
62 #include <errno.h>
63
64 #ifdef __CYGWIN__
65 #  include <fcntl.h>
66 #  include <io.h>
67 #endif
68
69 #include "../shell.h"
70 #include "common.h"
71 #include "bashgetopt.h"
72
73 #include <shtty.h>
74
75 #if defined (READLINE)
76 #include "../bashline.h"
77 #include <readline/readline.h>
78 #endif
79
80 #if !defined(errno)
81 extern int errno;
82 #endif
83
84 extern int interrupt_immediately;
85
86 #if defined (READLINE)
87 static char *edit_line __P((char *));
88 static void set_eol_delim __P((int));
89 static void reset_eol_delim __P((char *));
90 #endif
91 static SHELL_VAR *bind_read_variable __P((char *, char *));
92
93 static sighandler sigalrm __P((int));
94 static void reset_alarm __P((void));
95
96 static procenv_t alrmbuf;
97 static SigHandler *old_alrm;
98 static unsigned char delim;
99
100 static sighandler
101 sigalrm (s)
102      int s;
103 {
104   longjmp (alrmbuf, 1);
105 }
106
107 static void
108 reset_alarm ()
109 {
110   set_signal_handler (SIGALRM, old_alrm);
111   alarm (0);
112 }
113
114 /* Read the value of the shell variables whose names follow.
115    The reading is done from the current input stream, whatever
116    that may be.  Successive words of the input line are assigned
117    to the variables mentioned in LIST.  The last variable in LIST
118    gets the remainder of the words on the line.  If no variables
119    are mentioned in LIST, then the default variable is $REPLY. */
120 int
121 read_builtin (list)
122      WORD_LIST *list;
123 {
124   register char *varname;
125   int size, i, pass_next, saw_escape, eof, opt, retval, code;
126   int input_is_tty, input_is_pipe, unbuffered_read;
127   int raw, edit, nchars, silent, have_timeout, fd;
128   unsigned int tmout;
129   intmax_t intval;
130   char c;
131   char *input_string, *orig_input_string, *ifs_chars, *prompt, *arrayname;
132   char *e, *t, *t1;
133   struct stat tsb;
134   SHELL_VAR *var;
135 #if defined (ARRAY_VARS)
136   WORD_LIST *alist;
137 #endif
138 #if defined (READLINE)
139   char *rlbuf;
140   int rlind;
141 #endif
142
143   USE_VAR(size);
144   USE_VAR(i);
145   USE_VAR(pass_next);
146   USE_VAR(saw_escape);
147   USE_VAR(input_is_pipe);
148 /*  USE_VAR(raw); */
149   USE_VAR(edit);
150   USE_VAR(tmout);
151   USE_VAR(nchars);
152   USE_VAR(silent);
153   USE_VAR(ifs_chars);
154   USE_VAR(prompt);
155   USE_VAR(arrayname);
156 #if defined (READLINE)
157   USE_VAR(rlbuf);
158   USE_VAR(rlind);
159 #endif
160   USE_VAR(list);
161
162   i = 0;                /* Index into the string that we are reading. */
163   raw = edit = 0;       /* Not reading raw input by default. */
164   silent = 0;
165   arrayname = prompt = (char *)NULL;
166   fd = 0;               /* file descriptor to read from */
167
168 #if defined (READLINE)
169   rlbuf = (char *)0;
170   rlind = 0;
171 #endif
172
173   tmout = 0;            /* no timeout */
174   nchars = input_is_tty = input_is_pipe = unbuffered_read = have_timeout = 0;
175   delim = '\n';         /* read until newline */
176
177   reset_internal_getopt ();
178   while ((opt = internal_getopt (list, "ersa:d:n:p:t:u:")) != -1)
179     {
180       switch (opt)
181         {
182         case 'r':
183           raw = 1;
184           break;
185         case 'p':
186           prompt = list_optarg;
187           break;
188         case 's':
189           silent = 1;
190           break;
191         case 'e':
192 #if defined (READLINE)
193           edit = 1;
194 #endif
195           break;
196 #if defined (ARRAY_VARS)
197         case 'a':
198           arrayname = list_optarg;
199           break;
200 #endif
201         case 't':
202           code = legal_number (list_optarg, &intval);
203           if (code == 0 || intval < 0 || intval != (unsigned int)intval)
204             {
205               builtin_error ("%s: invalid timeout specification", list_optarg);
206               return (EXECUTION_FAILURE);
207             }
208           else
209             {
210               have_timeout = 1;
211               tmout = intval;
212             }
213           break;
214         case 'n':
215           code = legal_number (list_optarg, &intval);
216           if (code == 0 || intval < 0 || intval != (int)intval)
217             {
218               sh_invalidnum (list_optarg);
219               return (EXECUTION_FAILURE);
220             }
221           else
222             nchars = intval;
223           break;
224         case 'u':
225           code = legal_number (list_optarg, &intval);
226           if (code == 0 || intval < 0 || intval != (int)intval)
227             {
228               builtin_error ("%s: invalid file descriptor specification", list_optarg);
229               return (EXECUTION_FAILURE);
230             }
231           else
232             fd = intval;
233           if (sh_validfd (fd) == 0)
234             {
235               builtin_error ("%d: invalid file descriptor: %s", fd, strerror (errno));
236               return (EXECUTION_FAILURE);
237             }
238           break;
239         case 'd':
240           delim = *list_optarg;
241           break;
242         default:
243           builtin_usage ();
244           return (EX_USAGE);
245         }
246     }
247   list = loptend;
248
249   /* `read -t 0 var' returns failure immediately.  XXX - should it test
250      whether input is available with select/FIONREAD, and fail if those
251      are unavailable? */
252   if (have_timeout && tmout == 0)
253     return (EXECUTION_FAILURE);
254
255   /* IF IFS is unset, we use the default of " \t\n". */
256   ifs_chars = getifs ();
257   if (ifs_chars == 0)           /* XXX - shouldn't happen */
258     ifs_chars = "";
259
260   input_string = (char *)xmalloc (size = 112);  /* XXX was 128 */
261
262   /* $TMOUT, if set, is the default timeout for read. */
263   if (have_timeout == 0 && (e = get_string_value ("TMOUT")))
264     {
265       code = legal_number (e, &intval);
266       if (code == 0 || intval < 0 || intval != (unsigned int)intval)
267         tmout = 0;
268       else
269         tmout = intval;
270     }
271
272   begin_unwind_frame ("read_builtin");
273
274   input_is_tty = isatty (fd);
275   if (input_is_tty == 0)
276 #ifndef __CYGWIN__
277     input_is_pipe = (lseek (0, 0L, SEEK_CUR) < 0) && (errno == ESPIPE);
278 #else
279     input_is_pipe = 1;
280 #endif
281
282   /* If the -p, -e or -s flags were given, but input is not coming from the
283      terminal, turn them off. */
284   if ((prompt || edit || silent) && input_is_tty == 0)
285     {
286       prompt = (char *)NULL;
287       edit = silent = 0;
288     }
289
290 #if defined (READLINE)
291   if (edit)
292     add_unwind_protect (xfree, rlbuf);
293 #endif
294
295   if (prompt && edit == 0)
296     {
297       fprintf (stderr, "%s", prompt);
298       fflush (stderr);
299     }
300
301   pass_next = 0;        /* Non-zero signifies last char was backslash. */
302   saw_escape = 0;       /* Non-zero signifies that we saw an escape char */
303
304   if (tmout > 0)
305     {
306       /* Turn off the timeout if stdin is a regular file (e.g. from
307          input redirection). */
308       if ((fstat (fd, &tsb) < 0) || S_ISREG (tsb.st_mode))
309         tmout = 0;
310     }
311
312   if (tmout > 0)
313     {
314       code = setjmp (alrmbuf);
315       if (code)
316         {
317           run_unwind_frame ("read_builtin");
318           return (EXECUTION_FAILURE);
319         }
320       old_alrm = set_signal_handler (SIGALRM, sigalrm);
321       add_unwind_protect (reset_alarm, (char *)NULL);
322       alarm (tmout);
323     }
324
325   /* If we've been asked to read only NCHARS chars, or we're using some
326      character other than newline to terminate the line, do the right
327      thing to readline or the tty. */
328   if (nchars > 0 || delim != '\n')
329     {
330 #if defined (READLINE)
331       if (edit)
332         {
333           if (nchars > 0)
334             {
335               unwind_protect_int (rl_num_chars_to_read);
336               rl_num_chars_to_read = nchars;
337             }
338           if (delim != '\n')
339             {
340               set_eol_delim (delim);
341               add_unwind_protect (reset_eol_delim, (char *)NULL);
342             }
343         }
344       else
345 #endif
346       if (input_is_tty)
347         {
348           ttsave ();
349           if (silent)
350             ttcbreak ();
351           else
352             ttonechar ();
353           add_unwind_protect ((Function *)ttrestore, (char *)NULL);
354         }
355     }
356   else if (silent)      /* turn off echo but leave term in canonical mode */
357     {
358       ttsave ();
359       ttnoecho ();
360       add_unwind_protect ((Function *)ttrestore, (char *)NULL);
361     }
362
363   /* This *must* be the top unwind-protect on the stack, so the manipulation
364      of the unwind-protect stack after the realloc() works right. */
365   add_unwind_protect (xfree, input_string);
366   interrupt_immediately++;
367
368   unbuffered_read = (nchars > 0) || (delim != '\n') || input_is_pipe;
369
370 #if defined (__CYGWIN__) && defined (O_TEXT)
371   setmode (0, O_TEXT);
372 #endif
373
374   for (eof = retval = 0;;)
375     {
376 #if defined (READLINE)
377       if (edit)
378         {
379           if (rlbuf && rlbuf[rlind] == '\0')
380             {
381               xfree (rlbuf);
382               rlbuf = (char *)0;
383             }
384           if (rlbuf == 0)
385             {
386               rlbuf = edit_line (prompt ? prompt : "");
387               rlind = 0;
388             }
389           if (rlbuf == 0)
390             {
391               eof = 1;
392               break;
393             }
394           c = rlbuf[rlind++];
395         }
396       else
397         {
398 #endif
399
400       if (unbuffered_read)
401         retval = zread (fd, &c, 1);
402       else
403         retval = zreadc (fd, &c);
404
405       if (retval <= 0)
406         {
407           eof = 1;
408           break;
409         }
410
411 #if defined (READLINE)
412         }
413 #endif
414
415       if (i + 2 >= size)
416         {
417           input_string = (char *)xrealloc (input_string, size += 128);
418           remove_unwind_protect ();
419           add_unwind_protect (xfree, input_string);
420         }
421
422       /* If the next character is to be accepted verbatim, a backslash
423          newline pair still disappears from the input. */
424       if (pass_next)
425         {
426           if (c == '\n')
427             i--;                /* back up over the CTLESC */
428           else
429             input_string[i++] = c;
430           pass_next = 0;
431           continue;
432         }
433
434       if (c == '\\' && raw == 0)
435         {
436           pass_next++;
437           saw_escape++;
438           input_string[i++] = CTLESC;
439           continue;
440         }
441
442       if ((unsigned char)c == delim)
443         break;
444
445       if (c == CTLESC || c == CTLNUL)
446         {
447           saw_escape++;
448           input_string[i++] = CTLESC;
449         }
450
451       input_string[i++] = c;
452
453       if (nchars > 0 && i >= nchars)
454         break;
455     }
456   input_string[i] = '\0';
457
458 #if 1
459   if (retval < 0)
460     {
461       builtin_error ("read error: %d: %s", fd, strerror (errno));
462       return (EXECUTION_FAILURE);
463     }
464 #endif
465
466   if (tmout > 0)
467     reset_alarm ();
468
469   if (nchars > 0 || delim != '\n')
470     {
471 #if defined (READLINE)
472       if (edit)
473         {
474           if (nchars > 0)
475             rl_num_chars_to_read = 0;
476           if (delim != '\n')
477             reset_eol_delim ((char *)NULL);
478         }
479       else
480 #endif
481       if (input_is_tty)
482         ttrestore ();
483     }
484   else if (silent)
485     ttrestore ();
486
487   if (unbuffered_read == 0)
488     zsyncfd (fd);
489
490   interrupt_immediately--;
491   discard_unwind_frame ("read_builtin");
492
493   retval = eof ? EXECUTION_FAILURE : EXECUTION_SUCCESS;
494
495 #if defined (ARRAY_VARS)
496   /* If -a was given, take the string read, break it into a list of words,
497      an assign them to `arrayname' in turn. */
498   if (arrayname)
499     {
500       var = find_or_make_array_variable (arrayname, 1);
501       if (var == 0)
502         return EXECUTION_FAILURE;       /* readonly or noassign */
503       array_flush (array_cell (var));
504
505       alist = list_string (input_string, ifs_chars, 0);
506       if (alist)
507         {
508           assign_array_var_from_word_list (var, alist);
509           dispose_words (alist);
510         }
511       xfree (input_string);
512       return (retval);
513     }
514 #endif /* ARRAY_VARS */ 
515
516   /* If there are no variables, save the text of the line read to the
517      variable $REPLY.  ksh93 strips leading and trailing IFS whitespace,
518      so that `read x ; echo "$x"' and `read ; echo "$REPLY"' behave the
519      same way, but I believe that the difference in behaviors is useful
520      enough to not do it.  Without the bash behavior, there is no way
521      to read a line completely without interpretation or modification
522      unless you mess with $IFS (e.g., setting it to the empty string).
523      If you disagree, change the occurrences of `#if 0' to `#if 1' below. */
524   if (list == 0)
525     {
526 #if 0
527       orig_input_string = input_string;
528       for (t = input_string; ifs_chars && *ifs_chars && spctabnl(*t) && isifs(*t); t++)
529         ;
530       input_string = t;
531       input_string = strip_trailing_ifs_whitespace (input_string, ifs_chars, saw_escape);
532 #endif
533
534       if (saw_escape)
535         {
536           t = dequote_string (input_string);
537           var = bind_variable ("REPLY", t);
538           free (t);
539         }
540       else
541         var = bind_variable ("REPLY", input_string);
542       VUNSETATTR (var, att_invisible);
543
544       free (input_string);
545       return (retval);
546     }
547
548   /* This code implements the Posix.2 spec for splitting the words
549      read and assigning them to variables. */
550   orig_input_string = input_string;
551
552   /* Remove IFS white space at the beginning of the input string.  If
553      $IFS is null, no field splitting is performed. */
554   for (t = input_string; ifs_chars && *ifs_chars && spctabnl(*t) && isifs(*t); t++)
555     ;
556   input_string = t;
557
558   for (; list->next; list = list->next)
559     {
560       varname = list->word->word;
561 #if defined (ARRAY_VARS)
562       if (legal_identifier (varname) == 0 && valid_array_reference (varname) == 0)
563 #else
564       if (legal_identifier (varname) == 0)
565 #endif
566         {
567           sh_invalidid (varname);
568           xfree (orig_input_string);
569           return (EXECUTION_FAILURE);
570         }
571
572       /* If there are more variables than words read from the input,
573          the remaining variables are set to the empty string. */
574       if (*input_string)
575         {
576           /* This call updates INPUT_STRING. */
577           t = get_word_from_string (&input_string, ifs_chars, &e);
578           if (t)
579             *e = '\0';
580           /* Don't bother to remove the CTLESC unless we added one
581              somewhere while reading the string. */
582           if (t && saw_escape)
583             {
584               t1 = dequote_string (t);
585               var = bind_read_variable (varname, t1);
586               xfree (t1);
587             }
588           else
589             var = bind_read_variable (varname, t);
590         }
591       else
592         {
593           t = (char *)0;
594           var = bind_read_variable (varname, "");
595         }
596
597       FREE (t);
598       if (var == 0)
599         {
600           xfree (orig_input_string);
601           return (EXECUTION_FAILURE);
602         }
603
604       stupidly_hack_special_variables (varname);
605       VUNSETATTR (var, att_invisible);
606     }
607
608   /* Now assign the rest of the line to the last variable argument. */
609 #if defined (ARRAY_VARS)
610   if (legal_identifier (list->word->word) == 0 && valid_array_reference (list->word->word) == 0)
611 #else
612   if (legal_identifier (list->word->word) == 0)
613 #endif
614     {
615       sh_invalidid (list->word->word);
616       xfree (orig_input_string);
617       return (EXECUTION_FAILURE);
618     }
619
620   /* This has to be done this way rather than using string_list
621      and list_string because Posix.2 says that the last variable gets the
622      remaining words and their intervening separators. */
623   input_string = strip_trailing_ifs_whitespace (input_string, ifs_chars, saw_escape);
624
625   if (saw_escape)
626     {
627       t = dequote_string (input_string);
628       var = bind_read_variable (list->word->word, t);
629       xfree (t);
630     }
631   else
632     var = bind_read_variable (list->word->word, input_string);
633   stupidly_hack_special_variables (list->word->word);
634   if (var)
635     VUNSETATTR (var, att_invisible);
636   xfree (orig_input_string);
637
638   return (retval);
639 }
640
641 static SHELL_VAR *
642 bind_read_variable (name, value)
643      char *name, *value;
644 {
645 #if defined (ARRAY_VARS)
646   if (valid_array_reference (name) == 0)
647     return (bind_variable (name, value));
648   else
649     return (assign_array_element (name, value));
650 #else /* !ARRAY_VARS */
651   return bind_variable (name, value);
652 #endif /* !ARRAY_VARS */
653 }
654
655 #if defined (READLINE)
656 static rl_completion_func_t *old_attempted_completion_function;
657
658 static char *
659 edit_line (p)
660      char *p;
661 {
662   char *ret;
663   int len;
664
665   if (!bash_readline_initialized)
666     initialize_readline ();
667   old_attempted_completion_function = rl_attempted_completion_function;
668   rl_attempted_completion_function = (rl_completion_func_t *)NULL;
669   ret = readline (p);
670   rl_attempted_completion_function = old_attempted_completion_function;
671   if (ret == 0)
672     return ret;
673   len = strlen (ret);
674   ret = (char *)xrealloc (ret, len + 2);
675   ret[len++] = delim;
676   ret[len] = '\0';
677   return ret;
678 }
679
680 static int old_delim_ctype;
681 static rl_command_func_t *old_delim_func;
682 static int old_newline_ctype;
683 static rl_command_func_t *old_newline_func;
684
685 static unsigned char delim_char;
686
687 static void
688 set_eol_delim (c)
689      int c;
690 {
691   Keymap cmap;
692
693   if (bash_readline_initialized == 0)
694     initialize_readline ();
695   cmap = rl_get_keymap ();
696
697   /* Change newline to self-insert */
698   old_newline_ctype = cmap[RETURN].type;
699   old_newline_func =  cmap[RETURN].function;
700   cmap[RETURN].type = ISFUNC;
701   cmap[RETURN].function = rl_insert;
702
703   /* Bind the delimiter character to accept-line. */
704   old_delim_ctype = cmap[c].type;
705   old_delim_func = cmap[c].function;
706   cmap[c].type = ISFUNC;
707   cmap[c].function = rl_newline;
708
709   delim_char = c;
710 }
711
712 static void
713 reset_eol_delim (cp)
714      char *cp;
715 {
716   Keymap cmap;
717
718   cmap = rl_get_keymap ();
719
720   cmap[RETURN].type = old_newline_ctype;
721   cmap[RETURN].function = old_newline_func;
722
723   cmap[delim_char].type = old_delim_ctype;
724   cmap[delim_char].function = old_delim_func;
725 }
726 #endif