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