1 This file is read.def, from which is created read.c.
2 It implements the builtin "read" in Bash.
4 Copyright (C) 1987-2009 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] [-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
46 -p prompt output the string PROMPT without a trailing newline before
48 -r do not allow backslashes to escape any characters
49 -s do not echo input coming from a terminal
50 -t timeout time out and return failure if a complete line of input is
51 not read withint TIMEOUT seconds. The value of the TMOUT
52 variable is the default timeout. TIMEOUT may be a
53 fractional number. If TIMEOUT is 0, read returns success only
54 if input is available on the specified file descriptor. The
55 exit status is greater than 128 if the timeout is exceeded
56 -u fd read from file descriptor FD instead of the standard input
59 The return code is zero, unless end-of-file is encountered, read times out,
60 or an invalid file descriptor is supplied as the argument to -u.
65 #include "bashtypes.h"
66 #include "posixstat.h"
72 #if defined (HAVE_UNISTD_H)
84 #include "../bashintl.h"
88 #include "bashgetopt.h"
92 #if defined (READLINE)
93 #include "../bashline.h"
94 #include <readline/readline.h>
97 #if defined (BUFFERED_INPUT)
111 #if defined (READLINE)
112 static void reset_attempted_completion_function __P((char *));
113 static int set_itext __P((void));
114 static char *edit_line __P((char *, char *));
115 static void set_eol_delim __P((int));
116 static void reset_eol_delim __P((char *));
118 static SHELL_VAR *bind_read_variable __P((char *, char *));
119 #if defined (HANDLE_MULTIBYTE)
120 static int read_mbchar __P((int, char *, int, int, int));
122 static void ttyrestore __P((struct ttsave *));
124 static sighandler sigalrm __P((int));
125 static void reset_alarm __P((void));
127 static procenv_t alrmbuf;
128 static SigHandler *old_alrm;
129 static unsigned char delim;
135 longjmp (alrmbuf, 1);
141 set_signal_handler (SIGALRM, old_alrm);
145 /* Read the value of the shell variables whose names follow.
146 The reading is done from the current input stream, whatever
147 that may be. Successive words of the input line are assigned
148 to the variables mentioned in LIST. The last variable in LIST
149 gets the remainder of the words on the line. If no variables
150 are mentioned in LIST, then the default variable is $REPLY. */
155 register char *varname;
156 int size, i, nr, pass_next, saw_escape, eof, opt, retval, code, print_ps2;
157 int input_is_tty, input_is_pipe, unbuffered_read, skip_ctlesc, skip_ctlnul;
158 int raw, edit, nchars, silent, have_timeout, fd;
159 unsigned int tmsec, tmusec;
163 char *input_string, *orig_input_string, *ifs_chars, *prompt, *arrayname;
164 char *e, *t, *t1, *ps2, *tofree;
167 TTYSTRUCT ttattrs, ttset;
168 struct ttsave termsave;
169 #if defined (ARRAY_VARS)
172 #if defined (READLINE)
182 USE_VAR(input_is_pipe);
192 #if defined (READLINE)
200 i = 0; /* Index into the string that we are reading. */
201 raw = edit = 0; /* Not reading raw input by default. */
203 arrayname = prompt = (char *)NULL;
204 fd = 0; /* file descriptor to read from */
206 #if defined (READLINE)
207 rlbuf = itext = (char *)0;
211 tmsec = tmusec = 0; /* no timeout */
212 nr = nchars = input_is_tty = input_is_pipe = unbuffered_read = have_timeout = 0;
213 delim = '\n'; /* read until newline */
215 reset_internal_getopt ();
216 while ((opt = internal_getopt (list, "ersa:d:i:n:p:t:u:")) != -1)
224 prompt = list_optarg;
230 #if defined (READLINE)
235 #if defined (READLINE)
239 #if defined (ARRAY_VARS)
241 arrayname = list_optarg;
245 code = uconvert (list_optarg, &ival, &uval);
246 if (code == 0 || ival < 0 || uval < 0)
248 builtin_error (_("%s: invalid timeout specification"), list_optarg);
249 return (EXECUTION_FAILURE);
259 code = legal_number (list_optarg, &intval);
260 if (code == 0 || intval < 0 || intval != (int)intval)
262 sh_invalidnum (list_optarg);
263 return (EXECUTION_FAILURE);
269 code = legal_number (list_optarg, &intval);
270 if (code == 0 || intval < 0 || intval != (int)intval)
272 builtin_error (_("%s: invalid file descriptor specification"), list_optarg);
273 return (EXECUTION_FAILURE);
277 if (sh_validfd (fd) == 0)
279 builtin_error (_("%d: invalid file descriptor: %s"), fd, strerror (errno));
280 return (EXECUTION_FAILURE);
284 delim = *list_optarg;
293 /* `read -t 0 var' tests whether input is available with select/FIONREAD,
294 and fails if those are unavailable */
295 if (have_timeout && tmsec == 0 && tmusec == 0)
297 return (EXECUTION_FAILURE);
299 return (input_avail (fd) ? EXECUTION_SUCCESS : EXECUTION_FAILURE);
302 /* IF IFS is unset, we use the default of " \t\n". */
303 ifs_chars = getifs ();
304 if (ifs_chars == 0) /* XXX - shouldn't happen */
306 for (skip_ctlesc = skip_ctlnul = 0, e = ifs_chars; *e; e++)
307 skip_ctlesc |= *e == CTLESC, skip_ctlnul |= *e == CTLNUL;
309 input_string = (char *)xmalloc (size = 112); /* XXX was 128 */
310 input_string[0] = '\0';
312 /* $TMOUT, if set, is the default timeout for read. */
313 if (have_timeout == 0 && (e = get_string_value ("TMOUT")))
315 code = uconvert (e, &ival, &uval);
316 if (code == 0 || ival < 0 || uval < 0)
325 begin_unwind_frame ("read_builtin");
327 #if defined (BUFFERED_INPUT)
328 if (interactive == 0 && default_buffered_input >= 0 && fd_is_bash_input (fd))
329 sync_buffered_stream (default_buffered_input);
332 input_is_tty = isatty (fd);
333 if (input_is_tty == 0)
335 input_is_pipe = (lseek (fd, 0L, SEEK_CUR) < 0) && (errno == ESPIPE);
340 /* If the -p, -e or -s flags were given, but input is not coming from the
341 terminal, turn them off. */
342 if ((prompt || edit || silent) && input_is_tty == 0)
344 prompt = (char *)NULL;
345 #if defined (READLINE)
346 itext = (char *)NULL;
351 #if defined (READLINE)
353 add_unwind_protect (xfree, rlbuf);
356 pass_next = 0; /* Non-zero signifies last char was backslash. */
357 saw_escape = 0; /* Non-zero signifies that we saw an escape char */
359 if (tmsec > 0 || tmusec > 0)
361 /* Turn off the timeout if stdin is a regular file (e.g. from
362 input redirection). */
363 if ((fstat (fd, &tsb) < 0) || S_ISREG (tsb.st_mode))
367 if (tmsec > 0 || tmusec > 0)
369 code = setjmp (alrmbuf);
372 /* Tricky. The top of the unwind-protect stack is the free of
373 input_string. We want to run all the rest and use input_string,
374 so we have to remove it from the stack. */
375 remove_unwind_protect ();
376 run_unwind_frame ("read_builtin");
377 input_string[i] = '\0'; /* make sure it's terminated */
378 retval = 128+SIGALRM;
381 old_alrm = set_signal_handler (SIGALRM, sigalrm);
382 add_unwind_protect (reset_alarm, (char *)NULL);
383 #if defined (READLINE)
385 add_unwind_protect (reset_attempted_completion_function, (char *)NULL);
387 falarm (tmsec, tmusec);
390 /* If we've been asked to read only NCHARS chars, or we're using some
391 character other than newline to terminate the line, do the right
392 thing to readline or the tty. */
393 if (nchars > 0 || delim != '\n')
395 #if defined (READLINE)
400 unwind_protect_int (rl_num_chars_to_read);
401 rl_num_chars_to_read = nchars;
405 set_eol_delim (delim);
406 add_unwind_protect (reset_eol_delim, (char *)NULL);
415 ttgetattr (fd, &ttattrs);
416 termsave.attrs = &ttattrs;
419 i = silent ? ttfd_cbreak (fd, &ttset) : ttfd_onechar (fd, &ttset);
422 add_unwind_protect ((Function *)ttyrestore, (char *)&termsave);
425 else if (silent) /* turn off echo but leave term in canonical mode */
429 ttgetattr (fd, &ttattrs);
430 termsave.attrs = &ttattrs;
433 i = ttfd_noecho (fd, &ttset); /* ttnoecho (); */
437 add_unwind_protect ((Function *)ttyrestore, (char *)&termsave);
440 /* This *must* be the top unwind-protect on the stack, so the manipulation
441 of the unwind-protect stack after the realloc() works right. */
442 add_unwind_protect (xfree, input_string);
443 interrupt_immediately++;
444 terminate_immediately++;
446 unbuffered_read = (nchars > 0) || (delim != '\n') || input_is_pipe;
448 if (prompt && edit == 0)
450 fprintf (stderr, "%s", prompt);
454 #if defined (__CYGWIN__) && defined (O_TEXT)
459 for (print_ps2 = eof = retval = 0;;)
461 #if defined (READLINE)
464 if (rlbuf && rlbuf[rlind] == '\0')
471 rlbuf = edit_line (prompt ? prompt : "", itext);
488 ps2 = get_string_value ("PS2");
489 fprintf (stderr, "%s", ps2 ? ps2 : "");
495 retval = zread (fd, &c, 1);
497 retval = zreadc (fd, &c);
505 #if defined (READLINE)
509 if (i + 4 >= size) /* XXX was i + 2; use i + 4 for multibyte/read_mbchar */
511 input_string = (char *)xrealloc (input_string, size += 128);
512 remove_unwind_protect ();
513 add_unwind_protect (xfree, input_string);
516 /* If the next character is to be accepted verbatim, a backslash
517 newline pair still disappears from the input. */
523 i--; /* back up over the CTLESC */
524 if (interactive && input_is_tty && raw == 0)
532 /* This may cause problems if IFS contains CTLESC */
533 if (c == '\\' && raw == 0)
536 if (skip_ctlesc == 0)
539 input_string[i++] = CTLESC;
544 if ((unsigned char)c == delim)
547 if ((skip_ctlesc == 0 && c == CTLESC) || (skip_ctlnul == 0 && c == CTLNUL))
550 input_string[i++] = CTLESC;
554 input_string[i++] = c;
556 #if defined (HANDLE_MULTIBYTE)
557 if (nchars > 0 && MB_CUR_MAX > 1)
559 input_string[i] = '\0'; /* for simplicity and debugging */
560 i += read_mbchar (fd, input_string, i, c, unbuffered_read);
566 if (nchars > 0 && nr >= nchars)
569 input_string[i] = '\0';
574 builtin_error (_("read error: %d: %s"), fd, strerror (errno));
575 run_unwind_frame ("read_builtin");
576 return (EXECUTION_FAILURE);
580 if (tmsec > 0 || tmusec > 0)
583 if (nchars > 0 || delim != '\n')
585 #if defined (READLINE)
589 rl_num_chars_to_read = 0;
591 reset_eol_delim ((char *)NULL);
596 ttyrestore (&termsave);
599 ttyrestore (&termsave);
601 if (unbuffered_read == 0)
604 discard_unwind_frame ("read_builtin");
606 retval = eof ? EXECUTION_FAILURE : EXECUTION_SUCCESS;
610 interrupt_immediately--;
611 terminate_immediately--;
613 #if defined (ARRAY_VARS)
614 /* If -a was given, take the string read, break it into a list of words,
615 an assign them to `arrayname' in turn. */
618 if (legal_identifier (arrayname) == 0)
620 sh_invalidid (arrayname);
621 xfree (input_string);
622 return (EXECUTION_FAILURE);
625 var = find_or_make_array_variable (arrayname, 1);
628 xfree (input_string);
629 return EXECUTION_FAILURE; /* readonly or noassign */
631 array_flush (array_cell (var));
633 alist = list_string (input_string, ifs_chars, 0);
637 dequote_list (alist);
639 word_list_remove_quoted_nulls (alist);
640 assign_array_var_from_word_list (var, alist, 0);
641 dispose_words (alist);
643 xfree (input_string);
646 #endif /* ARRAY_VARS */
648 /* If there are no variables, save the text of the line read to the
649 variable $REPLY. ksh93 strips leading and trailing IFS whitespace,
650 so that `read x ; echo "$x"' and `read ; echo "$REPLY"' behave the
651 same way, but I believe that the difference in behaviors is useful
652 enough to not do it. Without the bash behavior, there is no way
653 to read a line completely without interpretation or modification
654 unless you mess with $IFS (e.g., setting it to the empty string).
655 If you disagree, change the occurrences of `#if 0' to `#if 1' below. */
659 orig_input_string = input_string;
660 for (t = input_string; ifs_chars && *ifs_chars && spctabnl(*t) && isifs(*t); t++)
663 input_string = strip_trailing_ifs_whitespace (input_string, ifs_chars, saw_escape);
668 t = dequote_string (input_string);
669 var = bind_variable ("REPLY", t, 0);
673 var = bind_variable ("REPLY", input_string, 0);
674 VUNSETATTR (var, att_invisible);
680 /* This code implements the Posix.2 spec for splitting the words
681 read and assigning them to variables. */
682 orig_input_string = input_string;
684 /* Remove IFS white space at the beginning of the input string. If
685 $IFS is null, no field splitting is performed. */
686 for (t = input_string; ifs_chars && *ifs_chars && spctabnl(*t) && isifs(*t); t++)
689 for (; list->next; list = list->next)
691 varname = list->word->word;
692 #if defined (ARRAY_VARS)
693 if (legal_identifier (varname) == 0 && valid_array_reference (varname) == 0)
695 if (legal_identifier (varname) == 0)
698 sh_invalidid (varname);
699 xfree (orig_input_string);
700 return (EXECUTION_FAILURE);
703 /* If there are more variables than words read from the input,
704 the remaining variables are set to the empty string. */
707 /* This call updates INPUT_STRING. */
708 t = get_word_from_string (&input_string, ifs_chars, &e);
711 /* Don't bother to remove the CTLESC unless we added one
712 somewhere while reading the string. */
715 t1 = dequote_string (t);
716 var = bind_read_variable (varname, t1);
720 var = bind_read_variable (varname, t);
725 var = bind_read_variable (varname, "");
731 xfree (orig_input_string);
732 return (EXECUTION_FAILURE);
735 stupidly_hack_special_variables (varname);
736 VUNSETATTR (var, att_invisible);
739 /* Now assign the rest of the line to the last variable argument. */
740 #if defined (ARRAY_VARS)
741 if (legal_identifier (list->word->word) == 0 && valid_array_reference (list->word->word) == 0)
743 if (legal_identifier (list->word->word) == 0)
746 sh_invalidid (list->word->word);
747 xfree (orig_input_string);
748 return (EXECUTION_FAILURE);
752 /* This has to be done this way rather than using string_list
753 and list_string because Posix.2 says that the last variable gets the
754 remaining words and their intervening separators. */
755 input_string = strip_trailing_ifs_whitespace (input_string, ifs_chars, saw_escape);
757 /* Check whether or not the number of fields is exactly the same as the
758 number of variables. */
763 t = get_word_from_string (&input_string, ifs_chars, &e);
764 if (*input_string == 0)
765 tofree = input_string = t;
768 input_string = strip_trailing_ifs_whitespace (t1, ifs_chars, saw_escape);
776 t = dequote_string (input_string);
777 var = bind_read_variable (list->word->word, t);
781 var = bind_read_variable (list->word->word, input_string);
782 stupidly_hack_special_variables (list->word->word);
786 VUNSETATTR (var, att_invisible);
787 xfree (orig_input_string);
793 bind_read_variable (name, value)
796 #if defined (ARRAY_VARS)
797 if (valid_array_reference (name) == 0)
798 return (bind_variable (name, value, 0));
800 return (assign_array_element (name, value, 0));
801 #else /* !ARRAY_VARS */
802 return bind_variable (name, value, 0);
803 #endif /* !ARRAY_VARS */
806 #if defined (HANDLE_MULTIBYTE)
808 read_mbchar (fd, string, ind, ch, unbuffered)
811 int ind, ch, unbuffered;
813 char mbchar[MB_LEN_MAX + 1];
817 mbstate_t ps, ps_back;
820 memset (&ps, '\0', sizeof (mbstate_t));
821 memset (&ps_back, '\0', sizeof (mbstate_t));
825 for (n = 0; n <= MB_LEN_MAX; n++)
828 ret = mbrtowc (&wc, mbchar, i, &ps);
829 if (ret == (size_t)-2)
833 r = zread (fd, &c, 1);
841 else if (ret == (size_t)-1 || ret == (size_t)0 || ret > (size_t)0)
846 if (i > 1) /* read a multibyte char */
847 /* mbchar[0] is already string[ind-1] */
848 for (r = 1; r < i; r++)
849 string[ind+r-1] = mbchar[r];
859 ttsetattr (ttp->fd, ttp->attrs);
862 #if defined (READLINE)
863 static rl_completion_func_t *old_attempted_completion_function = 0;
864 static rl_hook_func_t *old_startup_hook;
865 static char *deftext;
868 reset_attempted_completion_function (cp)
871 if (rl_attempted_completion_function == 0 && old_attempted_completion_function)
872 rl_attempted_completion_function = old_attempted_completion_function;
881 if (old_startup_hook)
882 r1 = (*old_startup_hook) ();
885 r2 = rl_insert_text (deftext);
886 deftext = (char *)NULL;
887 rl_startup_hook = old_startup_hook;
888 old_startup_hook = (rl_hook_func_t *)NULL;
901 if (bash_readline_initialized == 0)
902 initialize_readline ();
904 old_attempted_completion_function = rl_attempted_completion_function;
905 rl_attempted_completion_function = (rl_completion_func_t *)NULL;
908 old_startup_hook = rl_startup_hook;
909 rl_startup_hook = set_itext;
913 rl_attempted_completion_function = old_attempted_completion_function;
914 old_attempted_completion_function = (rl_completion_func_t *)NULL;
919 ret = (char *)xrealloc (ret, len + 2);
925 static int old_delim_ctype;
926 static rl_command_func_t *old_delim_func;
927 static int old_newline_ctype;
928 static rl_command_func_t *old_newline_func;
930 static unsigned char delim_char;
938 if (bash_readline_initialized == 0)
939 initialize_readline ();
940 cmap = rl_get_keymap ();
942 /* Change newline to self-insert */
943 old_newline_ctype = cmap[RETURN].type;
944 old_newline_func = cmap[RETURN].function;
945 cmap[RETURN].type = ISFUNC;
946 cmap[RETURN].function = rl_insert;
948 /* Bind the delimiter character to accept-line. */
949 old_delim_ctype = cmap[c].type;
950 old_delim_func = cmap[c].function;
951 cmap[c].type = ISFUNC;
952 cmap[c].function = rl_newline;
963 cmap = rl_get_keymap ();
965 cmap[RETURN].type = old_newline_ctype;
966 cmap[RETURN].function = old_newline_func;
968 cmap[delim_char].type = old_delim_ctype;
969 cmap[delim_char].function = old_delim_func;