afa549ed9d42122ad5a63ee060c6af6cfdaa5127
[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-2005 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 "../bashintl.h"
70
71 #include "../shell.h"
72 #include "common.h"
73 #include "bashgetopt.h"
74
75 #include <shtty.h>
76
77 #if defined (READLINE)
78 #include "../bashline.h"
79 #include <readline/readline.h>
80 #endif
81
82 #if defined (BUFFERED_INPUT)
83 #  include "input.h"
84 #endif
85
86 #if !defined(errno)
87 extern int errno;
88 #endif
89
90 #if defined (READLINE)
91 static void reset_attempted_completion_function __P((char *));
92 static char *edit_line __P((char *));
93 static void set_eol_delim __P((int));
94 static void reset_eol_delim __P((char *));
95 #endif
96 static SHELL_VAR *bind_read_variable __P((char *, char *));
97
98 static sighandler sigalrm __P((int));
99 static void reset_alarm __P((void));
100
101 static procenv_t alrmbuf;
102 static SigHandler *old_alrm;
103 static unsigned char delim;
104
105 static sighandler
106 sigalrm (s)
107      int s;
108 {
109   longjmp (alrmbuf, 1);
110 }
111
112 static void
113 reset_alarm ()
114 {
115   set_signal_handler (SIGALRM, old_alrm);
116   alarm (0);
117 }
118
119 /* Read the value of the shell variables whose names follow.
120    The reading is done from the current input stream, whatever
121    that may be.  Successive words of the input line are assigned
122    to the variables mentioned in LIST.  The last variable in LIST
123    gets the remainder of the words on the line.  If no variables
124    are mentioned in LIST, then the default variable is $REPLY. */
125 int
126 read_builtin (list)
127      WORD_LIST *list;
128 {
129   register char *varname;
130   int size, i, nr, pass_next, saw_escape, eof, opt, retval, code, print_ps2;
131   int input_is_tty, input_is_pipe, unbuffered_read, skip_ctlesc, skip_ctlnul;
132   int raw, edit, nchars, silent, have_timeout, fd;
133   unsigned int tmout;
134   intmax_t intval;
135   char c;
136   char *input_string, *orig_input_string, *ifs_chars, *prompt, *arrayname;
137   char *e, *t, *t1, *ps2, *tofree;
138   struct stat tsb;
139   SHELL_VAR *var;
140 #if defined (ARRAY_VARS)
141   WORD_LIST *alist;
142 #endif
143 #if defined (READLINE)
144   char *rlbuf;
145   int rlind;
146 #endif
147
148   USE_VAR(size);
149   USE_VAR(i);
150   USE_VAR(pass_next);
151   USE_VAR(print_ps2);
152   USE_VAR(saw_escape);
153   USE_VAR(input_is_pipe);
154 /*  USE_VAR(raw); */
155   USE_VAR(edit);
156   USE_VAR(tmout);
157   USE_VAR(nchars);
158   USE_VAR(silent);
159   USE_VAR(ifs_chars);
160   USE_VAR(prompt);
161   USE_VAR(arrayname);
162 #if defined (READLINE)
163   USE_VAR(rlbuf);
164   USE_VAR(rlind);
165 #endif
166   USE_VAR(list);
167   USE_VAR(ps2);
168
169   i = 0;                /* Index into the string that we are reading. */
170   raw = edit = 0;       /* Not reading raw input by default. */
171   silent = 0;
172   arrayname = prompt = (char *)NULL;
173   fd = 0;               /* file descriptor to read from */
174
175 #if defined (READLINE)
176   rlbuf = (char *)0;
177   rlind = 0;
178 #endif
179
180   tmout = 0;            /* no timeout */
181   nr = nchars = input_is_tty = input_is_pipe = unbuffered_read = have_timeout = 0;
182   delim = '\n';         /* read until newline */
183
184   reset_internal_getopt ();
185   while ((opt = internal_getopt (list, "ersa:d:n:p:t:u:")) != -1)
186     {
187       switch (opt)
188         {
189         case 'r':
190           raw = 1;
191           break;
192         case 'p':
193           prompt = list_optarg;
194           break;
195         case 's':
196           silent = 1;
197           break;
198         case 'e':
199 #if defined (READLINE)
200           edit = 1;
201 #endif
202           break;
203 #if defined (ARRAY_VARS)
204         case 'a':
205           arrayname = list_optarg;
206           break;
207 #endif
208         case 't':
209           code = legal_number (list_optarg, &intval);
210           if (code == 0 || intval < 0 || intval != (unsigned int)intval)
211             {
212               builtin_error (_("%s: invalid timeout specification"), list_optarg);
213               return (EXECUTION_FAILURE);
214             }
215           else
216             {
217               have_timeout = 1;
218               tmout = intval;
219             }
220           break;
221         case 'n':
222           code = legal_number (list_optarg, &intval);
223           if (code == 0 || intval < 0 || intval != (int)intval)
224             {
225               sh_invalidnum (list_optarg);
226               return (EXECUTION_FAILURE);
227             }
228           else
229             nchars = intval;
230           break;
231         case 'u':
232           code = legal_number (list_optarg, &intval);
233           if (code == 0 || intval < 0 || intval != (int)intval)
234             {
235               builtin_error (_("%s: invalid file descriptor specification"), list_optarg);
236               return (EXECUTION_FAILURE);
237             }
238           else
239             fd = intval;
240           if (sh_validfd (fd) == 0)
241             {
242               builtin_error (_("%d: invalid file descriptor: %s"), fd, strerror (errno));
243               return (EXECUTION_FAILURE);
244             }
245           break;
246         case 'd':
247           delim = *list_optarg;
248           break;
249         default:
250           builtin_usage ();
251           return (EX_USAGE);
252         }
253     }
254   list = loptend;
255
256   /* `read -t 0 var' returns failure immediately.  XXX - should it test
257      whether input is available with select/FIONREAD, and fail if those
258      are unavailable? */
259   if (have_timeout && tmout == 0)
260     return (EXECUTION_FAILURE);
261
262   /* IF IFS is unset, we use the default of " \t\n". */
263   ifs_chars = getifs ();
264   if (ifs_chars == 0)           /* XXX - shouldn't happen */
265     ifs_chars = "";
266
267   input_string = (char *)xmalloc (size = 112);  /* XXX was 128 */
268
269   /* $TMOUT, if set, is the default timeout for read. */
270   if (have_timeout == 0 && (e = get_string_value ("TMOUT")))
271     {
272       code = legal_number (e, &intval);
273       if (code == 0 || intval < 0 || intval != (unsigned int)intval)
274         tmout = 0;
275       else
276         tmout = intval;
277     }
278
279   begin_unwind_frame ("read_builtin");
280
281 #if defined (BUFFERED_INPUT)
282   if (interactive == 0 && default_buffered_input >= 0 && fd_is_bash_input (fd))
283     sync_buffered_stream (default_buffered_input);
284 #endif
285
286   input_is_tty = isatty (fd);
287   if (input_is_tty == 0)
288 #ifndef __CYGWIN__
289     input_is_pipe = (lseek (fd, 0L, SEEK_CUR) < 0) && (errno == ESPIPE);
290 #else
291     input_is_pipe = 1;
292 #endif
293
294   /* If the -p, -e or -s flags were given, but input is not coming from the
295      terminal, turn them off. */
296   if ((prompt || edit || silent) && input_is_tty == 0)
297     {
298       prompt = (char *)NULL;
299       edit = silent = 0;
300     }
301
302 #if defined (READLINE)
303   if (edit)
304     add_unwind_protect (xfree, rlbuf);
305 #endif
306
307   if (prompt && edit == 0)
308     {
309       fprintf (stderr, "%s", prompt);
310       fflush (stderr);
311     }
312
313   pass_next = 0;        /* Non-zero signifies last char was backslash. */
314   saw_escape = 0;       /* Non-zero signifies that we saw an escape char */
315
316   if (tmout > 0)
317     {
318       /* Turn off the timeout if stdin is a regular file (e.g. from
319          input redirection). */
320       if ((fstat (fd, &tsb) < 0) || S_ISREG (tsb.st_mode))
321         tmout = 0;
322     }
323
324   if (tmout > 0)
325     {
326       code = setjmp (alrmbuf);
327       if (code)
328         {
329           run_unwind_frame ("read_builtin");
330           return (EXECUTION_FAILURE);
331         }
332       old_alrm = set_signal_handler (SIGALRM, sigalrm);
333       add_unwind_protect (reset_alarm, (char *)NULL);
334 #if defined (READLINE)
335       if (edit)
336         add_unwind_protect (reset_attempted_completion_function, (char *)NULL);
337 #endif
338       alarm (tmout);
339     }
340
341   /* If we've been asked to read only NCHARS chars, or we're using some
342      character other than newline to terminate the line, do the right
343      thing to readline or the tty. */
344   if (nchars > 0 || delim != '\n')
345     {
346 #if defined (READLINE)
347       if (edit)
348         {
349           if (nchars > 0)
350             {
351               unwind_protect_int (rl_num_chars_to_read);
352               rl_num_chars_to_read = nchars;
353             }
354           if (delim != '\n')
355             {
356               set_eol_delim (delim);
357               add_unwind_protect (reset_eol_delim, (char *)NULL);
358             }
359         }
360       else
361 #endif
362       if (input_is_tty)
363         {
364           ttsave ();
365           if (silent)
366             ttcbreak ();
367           else
368             ttonechar ();
369           add_unwind_protect ((Function *)ttrestore, (char *)NULL);
370         }
371     }
372   else if (silent)      /* turn off echo but leave term in canonical mode */
373     {
374       ttsave ();
375       ttnoecho ();
376       add_unwind_protect ((Function *)ttrestore, (char *)NULL);
377     }
378
379   /* This *must* be the top unwind-protect on the stack, so the manipulation
380      of the unwind-protect stack after the realloc() works right. */
381   add_unwind_protect (xfree, input_string);
382   interrupt_immediately++;
383   terminate_immediately = 1;
384
385   unbuffered_read = (nchars > 0) || (delim != '\n') || input_is_pipe;
386
387 #if defined (__CYGWIN__) && defined (O_TEXT)
388   setmode (0, O_TEXT);
389 #endif
390
391   ps2 = 0;
392   for (print_ps2 = eof = retval = 0;;)
393     {
394 #if defined (READLINE)
395       if (edit)
396         {
397           if (rlbuf && rlbuf[rlind] == '\0')
398             {
399               xfree (rlbuf);
400               rlbuf = (char *)0;
401             }
402           if (rlbuf == 0)
403             {
404               rlbuf = edit_line (prompt ? prompt : "");
405               rlind = 0;
406             }
407           if (rlbuf == 0)
408             {
409               eof = 1;
410               break;
411             }
412           c = rlbuf[rlind++];
413         }
414       else
415         {
416 #endif
417
418       if (print_ps2)
419         {
420           if (ps2 == 0)
421             ps2 = get_string_value ("PS2");
422           fprintf (stderr, "%s", ps2 ? ps2 : "");
423           fflush (stderr);
424           print_ps2 = 0;
425         }
426
427       if (unbuffered_read)
428         retval = zread (fd, &c, 1);
429       else
430         retval = zreadc (fd, &c);
431
432       if (retval <= 0)
433         {
434           eof = 1;
435           break;
436         }
437
438 #if defined (READLINE)
439         }
440 #endif
441
442       if (i + 2 >= size)
443         {
444           input_string = (char *)xrealloc (input_string, size += 128);
445           remove_unwind_protect ();
446           add_unwind_protect (xfree, input_string);
447         }
448
449       /* If the next character is to be accepted verbatim, a backslash
450          newline pair still disappears from the input. */
451       if (pass_next)
452         {
453           pass_next = 0;
454           if (c == '\n')
455             {
456               i--;              /* back up over the CTLESC */
457               if (interactive && input_is_tty && raw == 0)
458                 print_ps2 = 1;
459             }
460           else
461             goto add_char;
462           continue;
463         }
464
465       if (c == '\\' && raw == 0)
466         {
467           pass_next++;
468           saw_escape++;
469           input_string[i++] = CTLESC;
470           continue;
471         }
472
473       if ((unsigned char)c == delim)
474         break;
475
476       if (c == CTLESC || c == CTLNUL)
477         {
478           saw_escape++;
479           input_string[i++] = CTLESC;
480         }
481
482 add_char:
483       input_string[i++] = c;
484       nr++;
485
486       if (nchars > 0 && nr >= nchars)
487         break;
488     }
489   input_string[i] = '\0';
490
491 #if 1
492   if (retval < 0)
493     {
494       builtin_error (_("read error: %d: %s"), fd, strerror (errno));
495       run_unwind_frame ("read_builtin");
496       return (EXECUTION_FAILURE);
497     }
498 #endif
499
500   if (tmout > 0)
501     reset_alarm ();
502
503   if (nchars > 0 || delim != '\n')
504     {
505 #if defined (READLINE)
506       if (edit)
507         {
508           if (nchars > 0)
509             rl_num_chars_to_read = 0;
510           if (delim != '\n')
511             reset_eol_delim ((char *)NULL);
512         }
513       else
514 #endif
515       if (input_is_tty)
516         ttrestore ();
517     }
518   else if (silent)
519     ttrestore ();
520
521   if (unbuffered_read == 0)
522     zsyncfd (fd);
523
524   interrupt_immediately--;
525   terminate_immediately = 0;
526   discard_unwind_frame ("read_builtin");
527
528   retval = eof ? EXECUTION_FAILURE : EXECUTION_SUCCESS;
529
530 #if defined (ARRAY_VARS)
531   /* If -a was given, take the string read, break it into a list of words,
532      an assign them to `arrayname' in turn. */
533   if (arrayname)
534     {
535       if (legal_identifier (arrayname) == 0)
536         {
537           sh_invalidid (arrayname);
538           xfree (input_string);
539           return (EXECUTION_FAILURE);
540         }
541
542       var = find_or_make_array_variable (arrayname, 1);
543       if (var == 0)
544         {
545           xfree (input_string);
546           return EXECUTION_FAILURE;     /* readonly or noassign */
547         }
548       array_flush (array_cell (var));
549
550       alist = list_string (input_string, ifs_chars, 0);
551       if (alist)
552         {
553           if (saw_escape)
554             dequote_list (alist);
555           else
556             word_list_remove_quoted_nulls (alist);
557           assign_array_var_from_word_list (var, alist, 0);
558           dispose_words (alist);
559         }
560       xfree (input_string);
561       return (retval);
562     }
563 #endif /* ARRAY_VARS */ 
564
565   /* If there are no variables, save the text of the line read to the
566      variable $REPLY.  ksh93 strips leading and trailing IFS whitespace,
567      so that `read x ; echo "$x"' and `read ; echo "$REPLY"' behave the
568      same way, but I believe that the difference in behaviors is useful
569      enough to not do it.  Without the bash behavior, there is no way
570      to read a line completely without interpretation or modification
571      unless you mess with $IFS (e.g., setting it to the empty string).
572      If you disagree, change the occurrences of `#if 0' to `#if 1' below. */
573   if (list == 0)
574     {
575 #if 0
576       orig_input_string = input_string;
577       for (t = input_string; ifs_chars && *ifs_chars && spctabnl(*t) && isifs(*t); t++)
578         ;
579       input_string = t;
580       input_string = strip_trailing_ifs_whitespace (input_string, ifs_chars, saw_escape);
581 #endif
582
583       if (saw_escape)
584         {
585           t = dequote_string (input_string);
586           var = bind_variable ("REPLY", t, 0);
587           free (t);
588         }
589       else
590         var = bind_variable ("REPLY", input_string, 0);
591       VUNSETATTR (var, att_invisible);
592
593       free (input_string);
594       return (retval);
595     }
596
597   /* This code implements the Posix.2 spec for splitting the words
598      read and assigning them to variables. */
599   orig_input_string = input_string;
600
601   /* Remove IFS white space at the beginning of the input string.  If
602      $IFS is null, no field splitting is performed. */
603   for (t = input_string; ifs_chars && *ifs_chars && spctabnl(*t) && isifs(*t); t++)
604     ;
605   input_string = t;
606
607   for (; list->next; list = list->next)
608     {
609       varname = list->word->word;
610 #if defined (ARRAY_VARS)
611       if (legal_identifier (varname) == 0 && valid_array_reference (varname) == 0)
612 #else
613       if (legal_identifier (varname) == 0)
614 #endif
615         {
616           sh_invalidid (varname);
617           xfree (orig_input_string);
618           return (EXECUTION_FAILURE);
619         }
620
621       /* If there are more variables than words read from the input,
622          the remaining variables are set to the empty string. */
623       if (*input_string)
624         {
625           /* This call updates INPUT_STRING. */
626           t = get_word_from_string (&input_string, ifs_chars, &e);
627           if (t)
628             *e = '\0';
629           /* Don't bother to remove the CTLESC unless we added one
630              somewhere while reading the string. */
631           if (t && saw_escape)
632             {
633               t1 = dequote_string (t);
634               var = bind_read_variable (varname, t1);
635               xfree (t1);
636             }
637           else
638             var = bind_read_variable (varname, t);
639         }
640       else
641         {
642           t = (char *)0;
643           var = bind_read_variable (varname, "");
644         }
645
646       FREE (t);
647       if (var == 0)
648         {
649           xfree (orig_input_string);
650           return (EXECUTION_FAILURE);
651         }
652
653       stupidly_hack_special_variables (varname);
654       VUNSETATTR (var, att_invisible);
655     }
656
657   /* Now assign the rest of the line to the last variable argument. */
658 #if defined (ARRAY_VARS)
659   if (legal_identifier (list->word->word) == 0 && valid_array_reference (list->word->word) == 0)
660 #else
661   if (legal_identifier (list->word->word) == 0)
662 #endif
663     {
664       sh_invalidid (list->word->word);
665       xfree (orig_input_string);
666       return (EXECUTION_FAILURE);
667     }
668
669 #if 0
670   /* This has to be done this way rather than using string_list
671      and list_string because Posix.2 says that the last variable gets the
672      remaining words and their intervening separators. */
673   input_string = strip_trailing_ifs_whitespace (input_string, ifs_chars, saw_escape);
674 #else
675   /* Check whether or not the number of fields is exactly the same as the
676      number of variables. */
677   tofree = NULL;
678   if (*input_string)
679     {
680       t1 = input_string;
681       t = get_word_from_string (&input_string, ifs_chars, &e);
682       if (*input_string == 0)
683         tofree = input_string = t;
684       else
685         input_string = strip_trailing_ifs_whitespace (t1, ifs_chars, saw_escape);
686     }
687 #endif
688
689   if (saw_escape)
690     {
691       t = dequote_string (input_string);
692       var = bind_read_variable (list->word->word, t);
693       xfree (t);
694     }
695   else
696     var = bind_read_variable (list->word->word, input_string);
697   stupidly_hack_special_variables (list->word->word);
698   FREE (tofree);
699
700   if (var)
701     VUNSETATTR (var, att_invisible);
702   xfree (orig_input_string);
703
704   return (retval);
705 }
706
707 static SHELL_VAR *
708 bind_read_variable (name, value)
709      char *name, *value;
710 {
711 #if defined (ARRAY_VARS)
712   if (valid_array_reference (name) == 0)
713     return (bind_variable (name, value, 0));
714   else
715     return (assign_array_element (name, value, 0));
716 #else /* !ARRAY_VARS */
717   return bind_variable (name, value, 0);
718 #endif /* !ARRAY_VARS */
719 }
720
721 #if defined (READLINE)
722 static rl_completion_func_t *old_attempted_completion_function = 0;
723
724 static void
725 reset_attempted_completion_function (cp)
726      char *cp;
727 {
728   if (rl_attempted_completion_function == 0 && old_attempted_completion_function)
729     rl_attempted_completion_function = old_attempted_completion_function;
730 }
731
732 static char *
733 edit_line (p)
734      char *p;
735 {
736   char *ret;
737   int len;
738
739   if (bash_readline_initialized == 0)
740     initialize_readline ();
741
742   old_attempted_completion_function = rl_attempted_completion_function;
743   rl_attempted_completion_function = (rl_completion_func_t *)NULL;
744   ret = readline (p);
745   rl_attempted_completion_function = old_attempted_completion_function;
746   old_attempted_completion_function = (rl_completion_func_t *)NULL;
747
748   if (ret == 0)
749     return ret;
750   len = strlen (ret);
751   ret = (char *)xrealloc (ret, len + 2);
752   ret[len++] = delim;
753   ret[len] = '\0';
754   return ret;
755 }
756
757 static int old_delim_ctype;
758 static rl_command_func_t *old_delim_func;
759 static int old_newline_ctype;
760 static rl_command_func_t *old_newline_func;
761
762 static unsigned char delim_char;
763
764 static void
765 set_eol_delim (c)
766      int c;
767 {
768   Keymap cmap;
769
770   if (bash_readline_initialized == 0)
771     initialize_readline ();
772   cmap = rl_get_keymap ();
773
774   /* Change newline to self-insert */
775   old_newline_ctype = cmap[RETURN].type;
776   old_newline_func =  cmap[RETURN].function;
777   cmap[RETURN].type = ISFUNC;
778   cmap[RETURN].function = rl_insert;
779
780   /* Bind the delimiter character to accept-line. */
781   old_delim_ctype = cmap[c].type;
782   old_delim_func = cmap[c].function;
783   cmap[c].type = ISFUNC;
784   cmap[c].function = rl_newline;
785
786   delim_char = c;
787 }
788
789 static void
790 reset_eol_delim (cp)
791      char *cp;
792 {
793   Keymap cmap;
794
795   cmap = rl_get_keymap ();
796
797   cmap[RETURN].type = old_newline_ctype;
798   cmap[RETURN].function = old_newline_func;
799
800   cmap[delim_char].type = old_delim_ctype;
801   cmap[delim_char].function = old_delim_func;
802 }
803 #endif