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