1 This file is read.def, from which is created read.c.
2 It implements the builtin "read" in Bash.
4 Copyright (C) 1987-2010 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
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 Bash is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with Bash. If not, see <http://www.gnu.org/licenses/>.
24 $FUNCTION read_builtin
25 $SHORT_DOC read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]
26 Read a line from the standard input and split it into fields.
28 Reads a single line from the standard input, or from file descriptor FD
29 if the -u option is supplied. The line is split into fields as with word
30 splitting, and the first word is assigned to the first NAME, the second
31 word to the second NAME, and so on, with any leftover words assigned to
32 the last NAME. Only the characters found in $IFS are recognized as word
35 If no NAMEs are supplied, the line read is stored in the REPLY variable.
38 -a array assign the words read to sequential indices of the array
39 variable ARRAY, starting at zero
40 -d delim continue until the first character of DELIM is read, rather
42 -e use Readline to obtain the line in an interactive shell
43 -i text Use TEXT as the initial text for Readline
44 -n nchars return after reading NCHARS characters rather than waiting
45 for a newline, but honor a delimiter if fewer than NCHARS
46 characters are read before the delimiter
47 -N nchars return only after reading exactly NCHARS characters, unless
48 EOF is encountered or read times out, ignoring any delimiter
49 -p prompt output the string PROMPT without a trailing newline before
51 -r do not allow backslashes to escape any characters
52 -s do not echo input coming from a terminal
53 -t timeout time out and return failure if a complete line of input is
54 not read withint TIMEOUT seconds. The value of the TMOUT
55 variable is the default timeout. TIMEOUT may be a
56 fractional number. If TIMEOUT is 0, read returns success only
57 if input is available on the specified file descriptor. The
58 exit status is greater than 128 if the timeout is exceeded
59 -u fd read from file descriptor FD instead of the standard input
62 The return code is zero, unless end-of-file is encountered, read times out,
63 or an invalid file descriptor is supplied as the argument to -u.
68 #include "bashtypes.h"
69 #include "posixstat.h"
75 #if defined (HAVE_UNISTD_H)
87 #include "../bashintl.h"
91 #include "bashgetopt.h"
95 #if defined (READLINE)
96 #include "../bashline.h"
97 #include <readline/readline.h>
100 #if defined (BUFFERED_INPUT)
114 #if defined (READLINE)
115 static void reset_attempted_completion_function __P((char *));
116 static int set_itext __P((void));
117 static char *edit_line __P((char *, char *));
118 static void set_eol_delim __P((int));
119 static void reset_eol_delim __P((char *));
121 static SHELL_VAR *bind_read_variable __P((char *, char *));
122 #if defined (HANDLE_MULTIBYTE)
123 static int read_mbchar __P((int, char *, int, int, int));
125 static void ttyrestore __P((struct ttsave *));
127 static sighandler sigalrm __P((int));
128 static void reset_alarm __P((void));
130 static procenv_t alrmbuf;
131 static SigHandler *old_alrm;
132 static unsigned char delim;
138 longjmp (alrmbuf, 1);
144 set_signal_handler (SIGALRM, old_alrm);
148 /* Read the value of the shell variables whose names follow.
149 The reading is done from the current input stream, whatever
150 that may be. Successive words of the input line are assigned
151 to the variables mentioned in LIST. The last variable in LIST
152 gets the remainder of the words on the line. If no variables
153 are mentioned in LIST, then the default variable is $REPLY. */
158 register char *varname;
159 int size, i, nr, pass_next, saw_escape, eof, opt, retval, code, print_ps2;
160 int input_is_tty, input_is_pipe, unbuffered_read, skip_ctlesc, skip_ctlnul;
161 int raw, edit, nchars, silent, have_timeout, ignore_delim, fd;
162 unsigned int tmsec, tmusec;
166 char *input_string, *orig_input_string, *ifs_chars, *prompt, *arrayname;
167 char *e, *t, *t1, *ps2, *tofree;
170 TTYSTRUCT ttattrs, ttset;
171 struct ttsave termsave;
172 #if defined (ARRAY_VARS)
175 #if defined (READLINE)
185 USE_VAR(input_is_pipe);
195 #if defined (READLINE)
203 i = 0; /* Index into the string that we are reading. */
204 raw = edit = 0; /* Not reading raw input by default. */
206 arrayname = prompt = (char *)NULL;
207 fd = 0; /* file descriptor to read from */
209 #if defined (READLINE)
210 rlbuf = itext = (char *)0;
214 tmsec = tmusec = 0; /* no timeout */
215 nr = nchars = input_is_tty = input_is_pipe = unbuffered_read = have_timeout = 0;
216 delim = '\n'; /* read until newline */
219 reset_internal_getopt ();
220 while ((opt = internal_getopt (list, "ersa:d:i:n:p:t:u:N:")) != -1)
228 prompt = list_optarg;
234 #if defined (READLINE)
239 #if defined (READLINE)
243 #if defined (ARRAY_VARS)
245 arrayname = list_optarg;
249 code = uconvert (list_optarg, &ival, &uval);
250 if (code == 0 || ival < 0 || uval < 0)
252 builtin_error (_("%s: invalid timeout specification"), list_optarg);
253 return (EXECUTION_FAILURE);
266 code = legal_number (list_optarg, &intval);
267 if (code == 0 || intval < 0 || intval != (int)intval)
269 sh_invalidnum (list_optarg);
270 return (EXECUTION_FAILURE);
276 code = legal_number (list_optarg, &intval);
277 if (code == 0 || intval < 0 || intval != (int)intval)
279 builtin_error (_("%s: invalid file descriptor specification"), list_optarg);
280 return (EXECUTION_FAILURE);
284 if (sh_validfd (fd) == 0)
286 builtin_error (_("%d: invalid file descriptor: %s"), fd, strerror (errno));
287 return (EXECUTION_FAILURE);
291 delim = *list_optarg;
300 /* `read -t 0 var' tests whether input is available with select/FIONREAD,
301 and fails if those are unavailable */
302 if (have_timeout && tmsec == 0 && tmusec == 0)
304 return (EXECUTION_FAILURE);
306 return (input_avail (fd) ? EXECUTION_SUCCESS : EXECUTION_FAILURE);
309 /* If we're asked to ignore the delimiter, make sure we do. */
313 /* IF IFS is unset, we use the default of " \t\n". */
314 ifs_chars = getifs ();
315 if (ifs_chars == 0) /* XXX - shouldn't happen */
317 /* If we want to read exactly NCHARS chars, don't split on IFS */
320 for (skip_ctlesc = skip_ctlnul = 0, e = ifs_chars; *e; e++)
321 skip_ctlesc |= *e == CTLESC, skip_ctlnul |= *e == CTLNUL;
323 input_string = (char *)xmalloc (size = 112); /* XXX was 128 */
324 input_string[0] = '\0';
326 /* $TMOUT, if set, is the default timeout for read. */
327 if (have_timeout == 0 && (e = get_string_value ("TMOUT")))
329 code = uconvert (e, &ival, &uval);
330 if (code == 0 || ival < 0 || uval < 0)
339 begin_unwind_frame ("read_builtin");
341 #if defined (BUFFERED_INPUT)
342 if (interactive == 0 && default_buffered_input >= 0 && fd_is_bash_input (fd))
343 sync_buffered_stream (default_buffered_input);
346 input_is_tty = isatty (fd);
347 if (input_is_tty == 0)
349 input_is_pipe = (lseek (fd, 0L, SEEK_CUR) < 0) && (errno == ESPIPE);
354 /* If the -p, -e or -s flags were given, but input is not coming from the
355 terminal, turn them off. */
356 if ((prompt || edit || silent) && input_is_tty == 0)
358 prompt = (char *)NULL;
359 #if defined (READLINE)
360 itext = (char *)NULL;
365 #if defined (READLINE)
367 add_unwind_protect (xfree, rlbuf);
370 pass_next = 0; /* Non-zero signifies last char was backslash. */
371 saw_escape = 0; /* Non-zero signifies that we saw an escape char */
373 if (tmsec > 0 || tmusec > 0)
375 /* Turn off the timeout if stdin is a regular file (e.g. from
376 input redirection). */
377 if ((fstat (fd, &tsb) < 0) || S_ISREG (tsb.st_mode))
381 if (tmsec > 0 || tmusec > 0)
383 code = setjmp (alrmbuf);
386 /* Tricky. The top of the unwind-protect stack is the free of
387 input_string. We want to run all the rest and use input_string,
388 so we have to remove it from the stack. */
389 remove_unwind_protect ();
390 run_unwind_frame ("read_builtin");
391 input_string[i] = '\0'; /* make sure it's terminated */
392 retval = 128+SIGALRM;
395 old_alrm = set_signal_handler (SIGALRM, sigalrm);
396 add_unwind_protect (reset_alarm, (char *)NULL);
397 #if defined (READLINE)
399 add_unwind_protect (reset_attempted_completion_function, (char *)NULL);
401 falarm (tmsec, tmusec);
404 /* If we've been asked to read only NCHARS chars, or we're using some
405 character other than newline to terminate the line, do the right
406 thing to readline or the tty. */
407 if (nchars > 0 || delim != '\n')
409 #if defined (READLINE)
414 unwind_protect_int (rl_num_chars_to_read);
415 rl_num_chars_to_read = nchars;
419 set_eol_delim (delim);
420 add_unwind_protect (reset_eol_delim, (char *)NULL);
429 ttgetattr (fd, &ttattrs);
430 termsave.attrs = &ttattrs;
433 i = silent ? ttfd_cbreak (fd, &ttset) : ttfd_onechar (fd, &ttset);
436 add_unwind_protect ((Function *)ttyrestore, (char *)&termsave);
439 else if (silent) /* turn off echo but leave term in canonical mode */
443 ttgetattr (fd, &ttattrs);
444 termsave.attrs = &ttattrs;
447 i = ttfd_noecho (fd, &ttset); /* ttnoecho (); */
451 add_unwind_protect ((Function *)ttyrestore, (char *)&termsave);
454 /* This *must* be the top unwind-protect on the stack, so the manipulation
455 of the unwind-protect stack after the realloc() works right. */
456 add_unwind_protect (xfree, input_string);
457 interrupt_immediately++;
458 terminate_immediately++;
460 unbuffered_read = (nchars > 0) || (delim != '\n') || input_is_pipe;
462 if (prompt && edit == 0)
464 fprintf (stderr, "%s", prompt);
468 #if defined (__CYGWIN__) && defined (O_TEXT)
473 for (print_ps2 = eof = retval = 0;;)
475 #if defined (READLINE)
478 if (rlbuf && rlbuf[rlind] == '\0')
485 rlbuf = edit_line (prompt ? prompt : "", itext);
502 ps2 = get_string_value ("PS2");
503 fprintf (stderr, "%s", ps2 ? ps2 : "");
509 retval = zread (fd, &c, 1);
511 retval = zreadc (fd, &c);
519 #if defined (READLINE)
523 if (i + 4 >= size) /* XXX was i + 2; use i + 4 for multibyte/read_mbchar */
525 input_string = (char *)xrealloc (input_string, size += 128);
526 remove_unwind_protect ();
527 add_unwind_protect (xfree, input_string);
530 /* If the next character is to be accepted verbatim, a backslash
531 newline pair still disappears from the input. */
537 i--; /* back up over the CTLESC */
538 if (interactive && input_is_tty && raw == 0)
546 /* This may cause problems if IFS contains CTLESC */
547 if (c == '\\' && raw == 0)
550 if (skip_ctlesc == 0)
553 input_string[i++] = CTLESC;
558 if ((unsigned char)c == delim)
561 if ((skip_ctlesc == 0 && c == CTLESC) || (skip_ctlnul == 0 && c == CTLNUL))
564 input_string[i++] = CTLESC;
568 input_string[i++] = c;
570 #if defined (HANDLE_MULTIBYTE)
571 if (nchars > 0 && MB_CUR_MAX > 1)
573 input_string[i] = '\0'; /* for simplicity and debugging */
574 i += read_mbchar (fd, input_string, i, c, unbuffered_read);
580 if (nchars > 0 && nr >= nchars)
583 input_string[i] = '\0';
588 builtin_error (_("read error: %d: %s"), fd, strerror (errno));
589 run_unwind_frame ("read_builtin");
590 return (EXECUTION_FAILURE);
594 if (tmsec > 0 || tmusec > 0)
597 if (nchars > 0 || delim != '\n')
599 #if defined (READLINE)
603 rl_num_chars_to_read = 0;
605 reset_eol_delim ((char *)NULL);
610 ttyrestore (&termsave);
613 ttyrestore (&termsave);
615 if (unbuffered_read == 0)
618 discard_unwind_frame ("read_builtin");
620 retval = eof ? EXECUTION_FAILURE : EXECUTION_SUCCESS;
624 interrupt_immediately--;
625 terminate_immediately--;
627 #if defined (ARRAY_VARS)
628 /* If -a was given, take the string read, break it into a list of words,
629 an assign them to `arrayname' in turn. */
632 if (legal_identifier (arrayname) == 0)
634 sh_invalidid (arrayname);
635 xfree (input_string);
636 return (EXECUTION_FAILURE);
639 var = find_or_make_array_variable (arrayname, 1);
642 xfree (input_string);
643 return EXECUTION_FAILURE; /* readonly or noassign */
645 array_flush (array_cell (var));
647 alist = list_string (input_string, ifs_chars, 0);
651 dequote_list (alist);
653 word_list_remove_quoted_nulls (alist);
654 assign_array_var_from_word_list (var, alist, 0);
655 dispose_words (alist);
657 xfree (input_string);
660 #endif /* ARRAY_VARS */
662 /* If there are no variables, save the text of the line read to the
663 variable $REPLY. ksh93 strips leading and trailing IFS whitespace,
664 so that `read x ; echo "$x"' and `read ; echo "$REPLY"' behave the
665 same way, but I believe that the difference in behaviors is useful
666 enough to not do it. Without the bash behavior, there is no way
667 to read a line completely without interpretation or modification
668 unless you mess with $IFS (e.g., setting it to the empty string).
669 If you disagree, change the occurrences of `#if 0' to `#if 1' below. */
673 orig_input_string = input_string;
674 for (t = input_string; ifs_chars && *ifs_chars && spctabnl(*t) && isifs(*t); t++)
677 input_string = strip_trailing_ifs_whitespace (input_string, ifs_chars, saw_escape);
682 t = dequote_string (input_string);
683 var = bind_variable ("REPLY", t, 0);
687 var = bind_variable ("REPLY", input_string, 0);
688 VUNSETATTR (var, att_invisible);
694 /* This code implements the Posix.2 spec for splitting the words
695 read and assigning them to variables. */
696 orig_input_string = input_string;
698 /* Remove IFS white space at the beginning of the input string. If
699 $IFS is null, no field splitting is performed. */
700 for (t = input_string; ifs_chars && *ifs_chars && spctabnl(*t) && isifs(*t); t++)
703 for (; list->next; list = list->next)
705 varname = list->word->word;
706 #if defined (ARRAY_VARS)
707 if (legal_identifier (varname) == 0 && valid_array_reference (varname) == 0)
709 if (legal_identifier (varname) == 0)
712 sh_invalidid (varname);
713 xfree (orig_input_string);
714 return (EXECUTION_FAILURE);
717 /* If there are more variables than words read from the input,
718 the remaining variables are set to the empty string. */
721 /* This call updates INPUT_STRING. */
722 t = get_word_from_string (&input_string, ifs_chars, &e);
725 /* Don't bother to remove the CTLESC unless we added one
726 somewhere while reading the string. */
729 t1 = dequote_string (t);
730 var = bind_read_variable (varname, t1);
734 var = bind_read_variable (varname, t);
739 var = bind_read_variable (varname, "");
745 xfree (orig_input_string);
746 return (EXECUTION_FAILURE);
749 stupidly_hack_special_variables (varname);
750 VUNSETATTR (var, att_invisible);
753 /* Now assign the rest of the line to the last variable argument. */
754 #if defined (ARRAY_VARS)
755 if (legal_identifier (list->word->word) == 0 && valid_array_reference (list->word->word) == 0)
757 if (legal_identifier (list->word->word) == 0)
760 sh_invalidid (list->word->word);
761 xfree (orig_input_string);
762 return (EXECUTION_FAILURE);
766 /* This has to be done this way rather than using string_list
767 and list_string because Posix.2 says that the last variable gets the
768 remaining words and their intervening separators. */
769 input_string = strip_trailing_ifs_whitespace (input_string, ifs_chars, saw_escape);
771 /* Check whether or not the number of fields is exactly the same as the
772 number of variables. */
777 t = get_word_from_string (&input_string, ifs_chars, &e);
778 if (*input_string == 0)
779 tofree = input_string = t;
782 input_string = strip_trailing_ifs_whitespace (t1, ifs_chars, saw_escape);
790 t = dequote_string (input_string);
791 var = bind_read_variable (list->word->word, t);
795 var = bind_read_variable (list->word->word, input_string);
799 stupidly_hack_special_variables (list->word->word);
800 VUNSETATTR (var, att_invisible);
803 retval = EXECUTION_FAILURE;
806 xfree (orig_input_string);
812 bind_read_variable (name, value)
816 #if defined (ARRAY_VARS)
817 if (valid_array_reference (name) == 0)
818 v = bind_variable (name, value, 0);
820 v = assign_array_element (name, value, 0);
821 #else /* !ARRAY_VARS */
822 v = bind_variable (name, value, 0);
823 #endif /* !ARRAY_VARS */
825 : ((readonly_p (v) || noassign_p (v)) ? (SHELL_VAR *)NULL : v));
828 #if defined (HANDLE_MULTIBYTE)
830 read_mbchar (fd, string, ind, ch, unbuffered)
833 int ind, ch, unbuffered;
835 char mbchar[MB_LEN_MAX + 1];
839 mbstate_t ps, ps_back;
842 memset (&ps, '\0', sizeof (mbstate_t));
843 memset (&ps_back, '\0', sizeof (mbstate_t));
847 for (n = 0; n <= MB_LEN_MAX; n++)
850 ret = mbrtowc (&wc, mbchar, i, &ps);
851 if (ret == (size_t)-2)
855 r = zread (fd, &c, 1);
863 else if (ret == (size_t)-1 || ret == (size_t)0 || ret > (size_t)0)
868 if (i > 1) /* read a multibyte char */
869 /* mbchar[0] is already string[ind-1] */
870 for (r = 1; r < i; r++)
871 string[ind+r-1] = mbchar[r];
881 ttsetattr (ttp->fd, ttp->attrs);
884 #if defined (READLINE)
885 static rl_completion_func_t *old_attempted_completion_function = 0;
886 static rl_hook_func_t *old_startup_hook;
887 static char *deftext;
890 reset_attempted_completion_function (cp)
893 if (rl_attempted_completion_function == 0 && old_attempted_completion_function)
894 rl_attempted_completion_function = old_attempted_completion_function;
903 if (old_startup_hook)
904 r1 = (*old_startup_hook) ();
907 r2 = rl_insert_text (deftext);
908 deftext = (char *)NULL;
909 rl_startup_hook = old_startup_hook;
910 old_startup_hook = (rl_hook_func_t *)NULL;
923 if (bash_readline_initialized == 0)
924 initialize_readline ();
926 old_attempted_completion_function = rl_attempted_completion_function;
927 rl_attempted_completion_function = (rl_completion_func_t *)NULL;
930 old_startup_hook = rl_startup_hook;
931 rl_startup_hook = set_itext;
935 rl_attempted_completion_function = old_attempted_completion_function;
936 old_attempted_completion_function = (rl_completion_func_t *)NULL;
941 ret = (char *)xrealloc (ret, len + 2);
947 static int old_delim_ctype;
948 static rl_command_func_t *old_delim_func;
949 static int old_newline_ctype;
950 static rl_command_func_t *old_newline_func;
952 static unsigned char delim_char;
960 if (bash_readline_initialized == 0)
961 initialize_readline ();
962 cmap = rl_get_keymap ();
964 /* Change newline to self-insert */
965 old_newline_ctype = cmap[RETURN].type;
966 old_newline_func = cmap[RETURN].function;
967 cmap[RETURN].type = ISFUNC;
968 cmap[RETURN].function = rl_insert;
970 /* Bind the delimiter character to accept-line. */
971 old_delim_ctype = cmap[c].type;
972 old_delim_func = cmap[c].function;
973 cmap[c].type = ISFUNC;
974 cmap[c].function = rl_newline;
985 cmap = rl_get_keymap ();
987 cmap[RETURN].type = old_newline_ctype;
988 cmap[RETURN].function = old_newline_func;
990 cmap[delim_char].type = old_delim_ctype;
991 cmap[delim_char].function = old_delim_func;