Patch-ID: bash32-017
[bash.git] / builtins / read.def
blob21521db0f21deaec21e94725378e2cf98d5bf793
1 This file is read.def, from which is created read.c.
2 It implements the builtin "read" in Bash.
4 Copyright (C) 1987-2005 Free Software Foundation, Inc.
6 This file is part of GNU Bash, the Bourne Again SHell.
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.
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.
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.
22 $PRODUCES read.c
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.
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
50 #include <config.h>
52 #include "bashtypes.h"
53 #include "posixstat.h"
55 #include <stdio.h>
57 #if defined (HAVE_UNISTD_H)
58 # include <unistd.h>
59 #endif
61 #include <signal.h>
62 #include <errno.h>
64 #ifdef __CYGWIN__
65 # include <fcntl.h>
66 # include <io.h>
67 #endif
69 #include "../bashintl.h"
71 #include "../shell.h"
72 #include "common.h"
73 #include "bashgetopt.h"
75 #include <shtty.h>
77 #if defined (READLINE)
78 #include "../bashline.h"
79 #include <readline/readline.h>
80 #endif
82 #if defined (BUFFERED_INPUT)
83 # include "input.h"
84 #endif
86 #if !defined(errno)
87 extern int errno;
88 #endif
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 *));
98 static sighandler sigalrm __P((int));
99 static void reset_alarm __P((void));
101 static procenv_t alrmbuf;
102 static SigHandler *old_alrm;
103 static unsigned char delim;
105 static sighandler
106 sigalrm (s)
107 int s;
109 longjmp (alrmbuf, 1);
112 static void
113 reset_alarm ()
115 set_signal_handler (SIGALRM, old_alrm);
116 alarm (0);
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. */
126 read_builtin (list)
127 WORD_LIST *list;
129 register char *varname;
130 int size, i, nr, pass_next, saw_escape, eof, opt, retval, code;
131 int input_is_tty, input_is_pipe, unbuffered_read;
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;
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
148 USE_VAR(size);
149 USE_VAR(i);
150 USE_VAR(pass_next);
151 USE_VAR(saw_escape);
152 USE_VAR(input_is_pipe);
153 /* USE_VAR(raw); */
154 USE_VAR(edit);
155 USE_VAR(tmout);
156 USE_VAR(nchars);
157 USE_VAR(silent);
158 USE_VAR(ifs_chars);
159 USE_VAR(prompt);
160 USE_VAR(arrayname);
161 #if defined (READLINE)
162 USE_VAR(rlbuf);
163 USE_VAR(rlind);
164 #endif
165 USE_VAR(list);
167 i = 0; /* Index into the string that we are reading. */
168 raw = edit = 0; /* Not reading raw input by default. */
169 silent = 0;
170 arrayname = prompt = (char *)NULL;
171 fd = 0; /* file descriptor to read from */
173 #if defined (READLINE)
174 rlbuf = (char *)0;
175 rlind = 0;
176 #endif
178 tmout = 0; /* no timeout */
179 nr = nchars = input_is_tty = input_is_pipe = unbuffered_read = have_timeout = 0;
180 delim = '\n'; /* read until newline */
182 reset_internal_getopt ();
183 while ((opt = internal_getopt (list, "ersa:d:n:p:t:u:")) != -1)
185 switch (opt)
187 case 'r':
188 raw = 1;
189 break;
190 case 'p':
191 prompt = list_optarg;
192 break;
193 case 's':
194 silent = 1;
195 break;
196 case 'e':
197 #if defined (READLINE)
198 edit = 1;
199 #endif
200 break;
201 #if defined (ARRAY_VARS)
202 case 'a':
203 arrayname = list_optarg;
204 break;
205 #endif
206 case 't':
207 code = legal_number (list_optarg, &intval);
208 if (code == 0 || intval < 0 || intval != (unsigned int)intval)
210 builtin_error (_("%s: invalid timeout specification"), list_optarg);
211 return (EXECUTION_FAILURE);
213 else
215 have_timeout = 1;
216 tmout = intval;
218 break;
219 case 'n':
220 code = legal_number (list_optarg, &intval);
221 if (code == 0 || intval < 0 || intval != (int)intval)
223 sh_invalidnum (list_optarg);
224 return (EXECUTION_FAILURE);
226 else
227 nchars = intval;
228 break;
229 case 'u':
230 code = legal_number (list_optarg, &intval);
231 if (code == 0 || intval < 0 || intval != (int)intval)
233 builtin_error (_("%s: invalid file descriptor specification"), list_optarg);
234 return (EXECUTION_FAILURE);
236 else
237 fd = intval;
238 if (sh_validfd (fd) == 0)
240 builtin_error (_("%d: invalid file descriptor: %s"), fd, strerror (errno));
241 return (EXECUTION_FAILURE);
243 break;
244 case 'd':
245 delim = *list_optarg;
246 break;
247 default:
248 builtin_usage ();
249 return (EX_USAGE);
252 list = loptend;
254 /* `read -t 0 var' returns failure immediately. XXX - should it test
255 whether input is available with select/FIONREAD, and fail if those
256 are unavailable? */
257 if (have_timeout && tmout == 0)
258 return (EXECUTION_FAILURE);
260 /* IF IFS is unset, we use the default of " \t\n". */
261 ifs_chars = getifs ();
262 if (ifs_chars == 0) /* XXX - shouldn't happen */
263 ifs_chars = "";
265 input_string = (char *)xmalloc (size = 112); /* XXX was 128 */
267 /* $TMOUT, if set, is the default timeout for read. */
268 if (have_timeout == 0 && (e = get_string_value ("TMOUT")))
270 code = legal_number (e, &intval);
271 if (code == 0 || intval < 0 || intval != (unsigned int)intval)
272 tmout = 0;
273 else
274 tmout = intval;
277 begin_unwind_frame ("read_builtin");
279 #if defined (BUFFERED_INPUT)
280 if (interactive == 0 && default_buffered_input >= 0 && fd_is_bash_input (fd))
281 sync_buffered_stream (default_buffered_input);
282 #endif
284 input_is_tty = isatty (fd);
285 if (input_is_tty == 0)
286 #ifndef __CYGWIN__
287 input_is_pipe = (lseek (fd, 0L, SEEK_CUR) < 0) && (errno == ESPIPE);
288 #else
289 input_is_pipe = 1;
290 #endif
292 /* If the -p, -e or -s flags were given, but input is not coming from the
293 terminal, turn them off. */
294 if ((prompt || edit || silent) && input_is_tty == 0)
296 prompt = (char *)NULL;
297 edit = silent = 0;
300 #if defined (READLINE)
301 if (edit)
302 add_unwind_protect (xfree, rlbuf);
303 #endif
305 if (prompt && edit == 0)
307 fprintf (stderr, "%s", prompt);
308 fflush (stderr);
311 pass_next = 0; /* Non-zero signifies last char was backslash. */
312 saw_escape = 0; /* Non-zero signifies that we saw an escape char */
314 if (tmout > 0)
316 /* Turn off the timeout if stdin is a regular file (e.g. from
317 input redirection). */
318 if ((fstat (fd, &tsb) < 0) || S_ISREG (tsb.st_mode))
319 tmout = 0;
322 if (tmout > 0)
324 code = setjmp (alrmbuf);
325 if (code)
327 run_unwind_frame ("read_builtin");
328 return (EXECUTION_FAILURE);
330 old_alrm = set_signal_handler (SIGALRM, sigalrm);
331 add_unwind_protect (reset_alarm, (char *)NULL);
332 #if defined (READLINE)
333 if (edit)
334 add_unwind_protect (reset_attempted_completion_function, (char *)NULL);
335 #endif
336 alarm (tmout);
339 /* If we've been asked to read only NCHARS chars, or we're using some
340 character other than newline to terminate the line, do the right
341 thing to readline or the tty. */
342 if (nchars > 0 || delim != '\n')
344 #if defined (READLINE)
345 if (edit)
347 if (nchars > 0)
349 unwind_protect_int (rl_num_chars_to_read);
350 rl_num_chars_to_read = nchars;
352 if (delim != '\n')
354 set_eol_delim (delim);
355 add_unwind_protect (reset_eol_delim, (char *)NULL);
358 else
359 #endif
360 if (input_is_tty)
362 ttsave ();
363 if (silent)
364 ttcbreak ();
365 else
366 ttonechar ();
367 add_unwind_protect ((Function *)ttrestore, (char *)NULL);
370 else if (silent) /* turn off echo but leave term in canonical mode */
372 ttsave ();
373 ttnoecho ();
374 add_unwind_protect ((Function *)ttrestore, (char *)NULL);
377 /* This *must* be the top unwind-protect on the stack, so the manipulation
378 of the unwind-protect stack after the realloc() works right. */
379 add_unwind_protect (xfree, input_string);
380 interrupt_immediately++;
381 terminate_immediately = 1;
383 unbuffered_read = (nchars > 0) || (delim != '\n') || input_is_pipe;
385 #if defined (__CYGWIN__) && defined (O_TEXT)
386 setmode (0, O_TEXT);
387 #endif
389 for (eof = retval = 0;;)
391 #if defined (READLINE)
392 if (edit)
394 if (rlbuf && rlbuf[rlind] == '\0')
396 xfree (rlbuf);
397 rlbuf = (char *)0;
399 if (rlbuf == 0)
401 rlbuf = edit_line (prompt ? prompt : "");
402 rlind = 0;
404 if (rlbuf == 0)
406 eof = 1;
407 break;
409 c = rlbuf[rlind++];
411 else
413 #endif
415 if (unbuffered_read)
416 retval = zread (fd, &c, 1);
417 else
418 retval = zreadc (fd, &c);
420 if (retval <= 0)
422 eof = 1;
423 break;
426 #if defined (READLINE)
428 #endif
430 if (i + 2 >= size)
432 input_string = (char *)xrealloc (input_string, size += 128);
433 remove_unwind_protect ();
434 add_unwind_protect (xfree, input_string);
437 /* If the next character is to be accepted verbatim, a backslash
438 newline pair still disappears from the input. */
439 if (pass_next)
441 pass_next = 0;
442 if (c == '\n')
443 i--; /* back up over the CTLESC */
444 else
445 goto add_char;
446 continue;
449 if (c == '\\' && raw == 0)
451 pass_next++;
452 saw_escape++;
453 input_string[i++] = CTLESC;
454 continue;
457 if ((unsigned char)c == delim)
458 break;
460 if (c == CTLESC || c == CTLNUL)
462 saw_escape++;
463 input_string[i++] = CTLESC;
466 add_char:
467 input_string[i++] = c;
468 nr++;
470 if (nchars > 0 && nr >= nchars)
471 break;
473 input_string[i] = '\0';
475 #if 1
476 if (retval < 0)
478 builtin_error (_("read error: %d: %s"), fd, strerror (errno));
479 run_unwind_frame ("read_builtin");
480 return (EXECUTION_FAILURE);
482 #endif
484 if (tmout > 0)
485 reset_alarm ();
487 if (nchars > 0 || delim != '\n')
489 #if defined (READLINE)
490 if (edit)
492 if (nchars > 0)
493 rl_num_chars_to_read = 0;
494 if (delim != '\n')
495 reset_eol_delim ((char *)NULL);
497 else
498 #endif
499 if (input_is_tty)
500 ttrestore ();
502 else if (silent)
503 ttrestore ();
505 if (unbuffered_read == 0)
506 zsyncfd (fd);
508 interrupt_immediately--;
509 terminate_immediately = 0;
510 discard_unwind_frame ("read_builtin");
512 retval = eof ? EXECUTION_FAILURE : EXECUTION_SUCCESS;
514 #if defined (ARRAY_VARS)
515 /* If -a was given, take the string read, break it into a list of words,
516 an assign them to `arrayname' in turn. */
517 if (arrayname)
519 if (legal_identifier (arrayname) == 0)
521 sh_invalidid (arrayname);
522 xfree (input_string);
523 return (EXECUTION_FAILURE);
526 var = find_or_make_array_variable (arrayname, 1);
527 if (var == 0)
529 xfree (input_string);
530 return EXECUTION_FAILURE; /* readonly or noassign */
532 array_flush (array_cell (var));
534 alist = list_string (input_string, ifs_chars, 0);
535 if (alist)
537 if (saw_escape)
538 dequote_list (alist);
539 else
540 word_list_remove_quoted_nulls (alist);
541 assign_array_var_from_word_list (var, alist, 0);
542 dispose_words (alist);
544 xfree (input_string);
545 return (retval);
547 #endif /* ARRAY_VARS */
549 /* If there are no variables, save the text of the line read to the
550 variable $REPLY. ksh93 strips leading and trailing IFS whitespace,
551 so that `read x ; echo "$x"' and `read ; echo "$REPLY"' behave the
552 same way, but I believe that the difference in behaviors is useful
553 enough to not do it. Without the bash behavior, there is no way
554 to read a line completely without interpretation or modification
555 unless you mess with $IFS (e.g., setting it to the empty string).
556 If you disagree, change the occurrences of `#if 0' to `#if 1' below. */
557 if (list == 0)
559 #if 0
560 orig_input_string = input_string;
561 for (t = input_string; ifs_chars && *ifs_chars && spctabnl(*t) && isifs(*t); t++)
563 input_string = t;
564 input_string = strip_trailing_ifs_whitespace (input_string, ifs_chars, saw_escape);
565 #endif
567 if (saw_escape)
569 t = dequote_string (input_string);
570 var = bind_variable ("REPLY", t, 0);
571 free (t);
573 else
574 var = bind_variable ("REPLY", input_string, 0);
575 VUNSETATTR (var, att_invisible);
577 free (input_string);
578 return (retval);
581 /* This code implements the Posix.2 spec for splitting the words
582 read and assigning them to variables. */
583 orig_input_string = input_string;
585 /* Remove IFS white space at the beginning of the input string. If
586 $IFS is null, no field splitting is performed. */
587 for (t = input_string; ifs_chars && *ifs_chars && spctabnl(*t) && isifs(*t); t++)
589 input_string = t;
591 for (; list->next; list = list->next)
593 varname = list->word->word;
594 #if defined (ARRAY_VARS)
595 if (legal_identifier (varname) == 0 && valid_array_reference (varname) == 0)
596 #else
597 if (legal_identifier (varname) == 0)
598 #endif
600 sh_invalidid (varname);
601 xfree (orig_input_string);
602 return (EXECUTION_FAILURE);
605 /* If there are more variables than words read from the input,
606 the remaining variables are set to the empty string. */
607 if (*input_string)
609 /* This call updates INPUT_STRING. */
610 t = get_word_from_string (&input_string, ifs_chars, &e);
611 if (t)
612 *e = '\0';
613 /* Don't bother to remove the CTLESC unless we added one
614 somewhere while reading the string. */
615 if (t && saw_escape)
617 t1 = dequote_string (t);
618 var = bind_read_variable (varname, t1);
619 xfree (t1);
621 else
622 var = bind_read_variable (varname, t);
624 else
626 t = (char *)0;
627 var = bind_read_variable (varname, "");
630 FREE (t);
631 if (var == 0)
633 xfree (orig_input_string);
634 return (EXECUTION_FAILURE);
637 stupidly_hack_special_variables (varname);
638 VUNSETATTR (var, att_invisible);
641 /* Now assign the rest of the line to the last variable argument. */
642 #if defined (ARRAY_VARS)
643 if (legal_identifier (list->word->word) == 0 && valid_array_reference (list->word->word) == 0)
644 #else
645 if (legal_identifier (list->word->word) == 0)
646 #endif
648 sh_invalidid (list->word->word);
649 xfree (orig_input_string);
650 return (EXECUTION_FAILURE);
653 #if 0
654 /* This has to be done this way rather than using string_list
655 and list_string because Posix.2 says that the last variable gets the
656 remaining words and their intervening separators. */
657 input_string = strip_trailing_ifs_whitespace (input_string, ifs_chars, saw_escape);
658 #else
659 /* Check whether or not the number of fields is exactly the same as the
660 number of variables. */
661 if (*input_string)
663 t1 = input_string;
664 t = get_word_from_string (&input_string, ifs_chars, &e);
665 if (*input_string == 0)
666 input_string = t;
667 else
668 input_string = strip_trailing_ifs_whitespace (t1, ifs_chars, saw_escape);
670 #endif
672 if (saw_escape)
674 t = dequote_string (input_string);
675 var = bind_read_variable (list->word->word, t);
676 xfree (t);
678 else
679 var = bind_read_variable (list->word->word, input_string);
680 stupidly_hack_special_variables (list->word->word);
681 if (var)
682 VUNSETATTR (var, att_invisible);
683 xfree (orig_input_string);
685 return (retval);
688 static SHELL_VAR *
689 bind_read_variable (name, value)
690 char *name, *value;
692 #if defined (ARRAY_VARS)
693 if (valid_array_reference (name) == 0)
694 return (bind_variable (name, value, 0));
695 else
696 return (assign_array_element (name, value, 0));
697 #else /* !ARRAY_VARS */
698 return bind_variable (name, value, 0);
699 #endif /* !ARRAY_VARS */
702 #if defined (READLINE)
703 static rl_completion_func_t *old_attempted_completion_function = 0;
705 static void
706 reset_attempted_completion_function (cp)
707 char *cp;
709 if (rl_attempted_completion_function == 0 && old_attempted_completion_function)
710 rl_attempted_completion_function = old_attempted_completion_function;
713 static char *
714 edit_line (p)
715 char *p;
717 char *ret;
718 int len;
720 if (bash_readline_initialized == 0)
721 initialize_readline ();
723 old_attempted_completion_function = rl_attempted_completion_function;
724 rl_attempted_completion_function = (rl_completion_func_t *)NULL;
725 ret = readline (p);
726 rl_attempted_completion_function = old_attempted_completion_function;
727 old_attempted_completion_function = (rl_completion_func_t *)NULL;
729 if (ret == 0)
730 return ret;
731 len = strlen (ret);
732 ret = (char *)xrealloc (ret, len + 2);
733 ret[len++] = delim;
734 ret[len] = '\0';
735 return ret;
738 static int old_delim_ctype;
739 static rl_command_func_t *old_delim_func;
740 static int old_newline_ctype;
741 static rl_command_func_t *old_newline_func;
743 static unsigned char delim_char;
745 static void
746 set_eol_delim (c)
747 int c;
749 Keymap cmap;
751 if (bash_readline_initialized == 0)
752 initialize_readline ();
753 cmap = rl_get_keymap ();
755 /* Change newline to self-insert */
756 old_newline_ctype = cmap[RETURN].type;
757 old_newline_func = cmap[RETURN].function;
758 cmap[RETURN].type = ISFUNC;
759 cmap[RETURN].function = rl_insert;
761 /* Bind the delimiter character to accept-line. */
762 old_delim_ctype = cmap[c].type;
763 old_delim_func = cmap[c].function;
764 cmap[c].type = ISFUNC;
765 cmap[c].function = rl_newline;
767 delim_char = c;
770 static void
771 reset_eol_delim (cp)
772 char *cp;
774 Keymap cmap;
776 cmap = rl_get_keymap ();
778 cmap[RETURN].type = old_newline_ctype;
779 cmap[RETURN].function = old_newline_func;
781 cmap[delim_char].type = old_delim_ctype;
782 cmap[delim_char].function = old_delim_func;
784 #endif