1 This file is read.def, from which is created read.c.
2 It implements the builtin "read" in Bash.
4 Copyright (C) 1987-2015 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
46 NCHARS 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
50 -p prompt output the string PROMPT without a trailing newline before
52 -r do not allow backslashes to escape any characters
53 -s do not echo input coming from a terminal
54 -t timeout time out and return failure if a complete line of
55 input is not read within TIMEOUT seconds. The value of the
56 TMOUT variable is the default timeout. TIMEOUT may be a
57 fractional number. If TIMEOUT is 0, read returns
58 immediately, without trying to read any data, returning
59 success only if input is available on the specified
60 file descriptor. The exit status is greater than 128
61 if the timeout is exceeded
62 -u fd read from file descriptor FD instead of the standard input
65 The return code is zero, unless end-of-file is encountered, read times out
66 (in which case it's greater than 128), a variable assignment error occurs,
67 or an invalid file descriptor is supplied as the argument to -u.
72 #include "bashtypes.h"
73 #include "posixstat.h"
79 #if defined (HAVE_UNISTD_H)
91 #include "../bashintl.h"
95 #include "bashgetopt.h"
99 #if defined (READLINE)
100 #include "../bashline.h"
101 #include <readline/readline.h>
104 #if defined (BUFFERED_INPUT)
108 #include "shmbutil.h"
114 extern void run_pending_traps __P((void));
116 extern int posixly_correct;
117 extern int trapped_signal_received;
125 #if defined (READLINE)
126 static void reset_attempted_completion_function __P((char *));
127 static int set_itext __P((void));
128 static char *edit_line __P((char *, char *));
129 static void set_eol_delim __P((int));
130 static void reset_eol_delim __P((char *));
132 static SHELL_VAR *bind_read_variable __P((char *, char *));
133 #if defined (HANDLE_MULTIBYTE)
134 static int read_mbchar __P((int, char *, int, int, int));
136 static void ttyrestore __P((struct ttsave *));
138 static sighandler sigalrm __P((int));
139 static void reset_alarm __P((void));
141 /* Try this to see what the rest of the shell can do with the information. */
145 static int reading, tty_modified;
146 static SigHandler *old_alrm;
147 static unsigned char delim;
149 static struct ttsave termsave;
151 /* In all cases, SIGALRM just sets a flag that we check periodically. This
152 avoids problems with the semi-tricky stuff we do with the xfree of
153 input_string at the top of the unwind-protect list (see below). */
155 /* Set a flag that CHECK_ALRM can check. This relies on zread calling
156 trap.c:check_signals_and_traps(), which knows about sigalrm_seen and
168 /* Cancel alarm before restoring signal handler. */
170 set_signal_handler (SIGALRM, old_alrm);
173 /* Read the value of the shell variables whose names follow.
174 The reading is done from the current input stream, whatever
175 that may be. Successive words of the input line are assigned
176 to the variables mentioned in LIST. The last variable in LIST
177 gets the remainder of the words on the line. If no variables
178 are mentioned in LIST, then the default variable is $REPLY. */
183 register char *varname;
184 int size, nr, pass_next, saw_escape, eof, opt, retval, code, print_ps2;
186 int input_is_tty, input_is_pipe, unbuffered_read, skip_ctlesc, skip_ctlnul;
187 int raw, edit, nchars, silent, have_timeout, ignore_delim, fd, lastsig, t_errno;
188 unsigned int tmsec, tmusec;
192 char *input_string, *orig_input_string, *ifs_chars, *prompt, *arrayname;
193 char *e, *t, *t1, *ps2, *tofree;
196 TTYSTRUCT ttattrs, ttset;
197 #if defined (ARRAY_VARS)
200 #if defined (READLINE)
210 USE_VAR(input_is_pipe);
220 #if defined (READLINE)
229 sigalrm_seen = reading = tty_modified = 0;
231 i = 0; /* Index into the string that we are reading. */
232 raw = edit = 0; /* Not reading raw input by default. */
234 arrayname = prompt = (char *)NULL;
235 fd = 0; /* file descriptor to read from */
237 #if defined (READLINE)
238 rlbuf = itext = (char *)0;
242 tmsec = tmusec = 0; /* no timeout */
243 nr = nchars = input_is_tty = input_is_pipe = unbuffered_read = have_timeout = 0;
244 delim = '\n'; /* read until newline */
247 reset_internal_getopt ();
248 while ((opt = internal_getopt (list, "ersa:d:i:n:p:t:u:N:")) != -1)
256 prompt = list_optarg;
262 #if defined (READLINE)
267 #if defined (READLINE)
271 #if defined (ARRAY_VARS)
273 arrayname = list_optarg;
277 code = uconvert (list_optarg, &ival, &uval);
278 if (code == 0 || ival < 0 || uval < 0)
280 builtin_error (_("%s: invalid timeout specification"), list_optarg);
281 return (EXECUTION_FAILURE);
294 code = legal_number (list_optarg, &intval);
295 if (code == 0 || intval < 0 || intval != (int)intval)
297 sh_invalidnum (list_optarg);
298 return (EXECUTION_FAILURE);
304 code = legal_number (list_optarg, &intval);
305 if (code == 0 || intval < 0 || intval != (int)intval)
307 builtin_error (_("%s: invalid file descriptor specification"), list_optarg);
308 return (EXECUTION_FAILURE);
312 if (sh_validfd (fd) == 0)
314 builtin_error (_("%d: invalid file descriptor: %s"), fd, strerror (errno));
315 return (EXECUTION_FAILURE);
319 delim = *list_optarg;
329 /* `read -t 0 var' tests whether input is available with select/FIONREAD,
330 and fails if those are unavailable */
331 if (have_timeout && tmsec == 0 && tmusec == 0)
333 return (EXECUTION_FAILURE);
335 return (input_avail (fd) ? EXECUTION_SUCCESS : EXECUTION_FAILURE);
338 /* Convenience: check early whether or not the first of possibly several
339 variable names is a valid identifier, and bail early if so. */
340 #if defined (ARRAY_VARS)
341 if (list && legal_identifier (list->word->word) == 0 && valid_array_reference (list->word->word, 0) == 0)
343 if (list && legal_identifier (list->word->word) == 0)
346 sh_invalidid (list->word->word);
347 return (EXECUTION_FAILURE);
350 /* If we're asked to ignore the delimiter, make sure we do. */
354 /* IF IFS is unset, we use the default of " \t\n". */
355 ifs_chars = getifs ();
356 if (ifs_chars == 0) /* XXX - shouldn't happen */
358 /* If we want to read exactly NCHARS chars, don't split on IFS */
361 for (skip_ctlesc = skip_ctlnul = 0, e = ifs_chars; *e; e++)
362 skip_ctlesc |= *e == CTLESC, skip_ctlnul |= *e == CTLNUL;
364 input_string = (char *)xmalloc (size = 112); /* XXX was 128 */
365 input_string[0] = '\0';
367 /* $TMOUT, if set, is the default timeout for read. */
368 if (have_timeout == 0 && (e = get_string_value ("TMOUT")))
370 code = uconvert (e, &ival, &uval);
371 if (code == 0 || ival < 0 || uval < 0)
380 begin_unwind_frame ("read_builtin");
382 #if defined (BUFFERED_INPUT)
383 if (interactive == 0 && default_buffered_input >= 0 && fd_is_bash_input (fd))
384 sync_buffered_stream (default_buffered_input);
387 input_is_tty = isatty (fd);
388 if (input_is_tty == 0)
390 input_is_pipe = (lseek (fd, 0L, SEEK_CUR) < 0) && (errno == ESPIPE);
395 /* If the -p, -e or -s flags were given, but input is not coming from the
396 terminal, turn them off. */
397 if ((prompt || edit || silent) && input_is_tty == 0)
399 prompt = (char *)NULL;
400 #if defined (READLINE)
401 itext = (char *)NULL;
406 #if defined (READLINE)
408 add_unwind_protect (xfree, rlbuf);
411 pass_next = 0; /* Non-zero signifies last char was backslash. */
412 saw_escape = 0; /* Non-zero signifies that we saw an escape char */
414 if (tmsec > 0 || tmusec > 0)
416 /* Turn off the timeout if stdin is a regular file (e.g. from
417 input redirection). */
418 if ((fstat (fd, &tsb) < 0) || S_ISREG (tsb.st_mode))
422 if (tmsec > 0 || tmusec > 0)
424 code = setjmp_nosigs (alrmbuf);
428 /* Tricky. The top of the unwind-protect stack is the free of
429 input_string. We want to run all the rest and use input_string,
430 so we have to save input_string temporarily, run the unwind-
431 protects, then restore input_string so we can use it later */
432 orig_input_string = 0;
433 input_string[i] = '\0'; /* make sure it's terminated */
436 t = (char *)xmalloc (1);
440 t = savestring (input_string);
442 run_unwind_frame ("read_builtin");
444 retval = 128+SIGALRM;
447 if (interactive_shell == 0)
448 initialize_terminating_signals ();
449 old_alrm = set_signal_handler (SIGALRM, sigalrm);
450 add_unwind_protect (reset_alarm, (char *)NULL);
451 #if defined (READLINE)
454 add_unwind_protect (reset_attempted_completion_function, (char *)NULL);
455 add_unwind_protect (bashline_reset_event_hook, (char *)NULL);
458 falarm (tmsec, tmusec);
461 /* If we've been asked to read only NCHARS chars, or we're using some
462 character other than newline to terminate the line, do the right
463 thing to readline or the tty. */
464 if (nchars > 0 || delim != '\n')
466 #if defined (READLINE)
471 unwind_protect_int (rl_num_chars_to_read);
472 rl_num_chars_to_read = nchars;
476 set_eol_delim (delim);
477 add_unwind_protect (reset_eol_delim, (char *)NULL);
486 ttgetattr (fd, &ttattrs);
487 termsave.attrs = &ttattrs;
490 i = silent ? ttfd_cbreak (fd, &ttset) : ttfd_onechar (fd, &ttset);
494 add_unwind_protect ((Function *)ttyrestore, (char *)&termsave);
495 if (interactive_shell == 0)
496 initialize_terminating_signals ();
499 else if (silent) /* turn off echo but leave term in canonical mode */
503 ttgetattr (fd, &ttattrs);
504 termsave.attrs = &ttattrs;
507 i = ttfd_noecho (fd, &ttset); /* ttnoecho (); */
512 add_unwind_protect ((Function *)ttyrestore, (char *)&termsave);
513 if (interactive_shell == 0)
514 initialize_terminating_signals ();
517 /* This *must* be the top unwind-protect on the stack, so the manipulation
518 of the unwind-protect stack after the realloc() works right. */
519 add_unwind_protect (xfree, input_string);
522 if ((nchars > 0) && (input_is_tty == 0) && ignore_delim) /* read -N */
524 else if ((nchars > 0) || (delim != '\n') || input_is_pipe)
527 if (prompt && edit == 0)
529 fprintf (stderr, "%s", prompt);
533 #if defined (__CYGWIN__) && defined (O_TEXT)
538 for (print_ps2 = eof = retval = 0;;)
542 #if defined (READLINE)
545 if (rlbuf && rlbuf[rlind] == '\0')
553 rlbuf = edit_line (prompt ? prompt : "", itext);
571 ps2 = get_string_value ("PS2");
572 fprintf (stderr, "%s", ps2 ? ps2 : "");
578 if (posixly_correct == 0)
579 interrupt_immediately++;
582 if (unbuffered_read == 2)
583 retval = posixly_correct ? zreadintr (fd, &c, 1) : zreadn (fd, &c, nchars - nr);
584 else if (unbuffered_read)
585 retval = posixly_correct ? zreadintr (fd, &c, 1) : zread (fd, &c, 1);
587 retval = posixly_correct ? zreadcintr (fd, &c) : zreadc (fd, &c);
590 if (posixly_correct == 0)
591 interrupt_immediately--;
596 if (retval < 0 && errno == EINTR)
600 lastsig = trapped_signal_received;
601 run_pending_traps (); /* because interrupt_immediately is not set */
605 if (terminating_signal && tty_modified)
606 ttyrestore (&termsave); /* fix terminal before exiting */
614 #if defined (READLINE)
619 if (i + 4 >= size) /* XXX was i + 2; use i + 4 for multibyte/read_mbchar */
622 t = (char *)xrealloc (input_string, size += 128);
624 /* Only need to change unwind-protect if input_string changes */
625 if (t != input_string)
628 remove_unwind_protect ();
629 add_unwind_protect (xfree, input_string);
633 /* If the next character is to be accepted verbatim, a backslash
634 newline pair still disappears from the input. */
640 i--; /* back up over the CTLESC */
641 if (interactive && input_is_tty && raw == 0)
649 /* This may cause problems if IFS contains CTLESC */
650 if (c == '\\' && raw == 0)
653 if (skip_ctlesc == 0)
656 input_string[i++] = CTLESC;
661 if (ignore_delim == 0 && (unsigned char)c == delim)
664 if (c == '\0' && delim != '\0')
665 continue; /* skip NUL bytes in input */
667 if ((skip_ctlesc == 0 && c == CTLESC) || (skip_ctlnul == 0 && c == CTLNUL))
670 input_string[i++] = CTLESC;
674 input_string[i++] = c;
677 #if defined (HANDLE_MULTIBYTE)
678 if (nchars > 0 && MB_CUR_MAX > 1 && is_basic (c) == 0)
680 input_string[i] = '\0'; /* for simplicity and debugging */
681 i += read_mbchar (fd, input_string, i, c, unbuffered_read);
687 if (nchars > 0 && nr >= nchars)
690 input_string[i] = '\0';
693 #if defined (READLINE)
702 builtin_error (_("read error: %d: %s"), fd, strerror (errno));
703 run_unwind_frame ("read_builtin");
704 return ((t_errno != EINTR) ? EXECUTION_FAILURE : 128+lastsig);
707 if (tmsec > 0 || tmusec > 0)
710 if (nchars > 0 || delim != '\n')
712 #if defined (READLINE)
716 rl_num_chars_to_read = 0;
718 reset_eol_delim ((char *)NULL);
723 ttyrestore (&termsave);
726 ttyrestore (&termsave);
728 if (unbuffered_read == 0)
731 discard_unwind_frame ("read_builtin");
733 retval = eof ? EXECUTION_FAILURE : EXECUTION_SUCCESS;
737 #if defined (ARRAY_VARS)
738 /* If -a was given, take the string read, break it into a list of words,
739 an assign them to `arrayname' in turn. */
742 if (legal_identifier (arrayname) == 0)
744 sh_invalidid (arrayname);
745 xfree (input_string);
746 return (EXECUTION_FAILURE);
749 var = find_or_make_array_variable (arrayname, 1);
752 xfree (input_string);
753 return EXECUTION_FAILURE; /* readonly or noassign */
757 builtin_error (_("%s: cannot convert associative to indexed array"), arrayname);
758 xfree (input_string);
759 return EXECUTION_FAILURE; /* existing associative array */
761 else if (invisible_p (var))
762 VUNSETATTR (var, att_invisible);
763 array_flush (array_cell (var));
765 alist = list_string (input_string, ifs_chars, 0);
769 dequote_list (alist);
771 word_list_remove_quoted_nulls (alist);
772 assign_array_var_from_word_list (var, alist, 0);
773 dispose_words (alist);
775 xfree (input_string);
778 #endif /* ARRAY_VARS */
780 /* If there are no variables, save the text of the line read to the
781 variable $REPLY. ksh93 strips leading and trailing IFS whitespace,
782 so that `read x ; echo "$x"' and `read ; echo "$REPLY"' behave the
783 same way, but I believe that the difference in behaviors is useful
784 enough to not do it. Without the bash behavior, there is no way
785 to read a line completely without interpretation or modification
786 unless you mess with $IFS (e.g., setting it to the empty string).
787 If you disagree, change the occurrences of `#if 0' to `#if 1' below. */
791 orig_input_string = input_string;
792 for (t = input_string; ifs_chars && *ifs_chars && spctabnl(*t) && isifs(*t); t++)
795 input_string = strip_trailing_ifs_whitespace (input_string, ifs_chars, saw_escape);
800 t = dequote_string (input_string);
801 var = bind_variable ("REPLY", t, 0);
805 var = bind_variable ("REPLY", input_string, 0);
806 if (var == 0 || readonly_p (var) || noassign_p (var))
807 retval = EXECUTION_FAILURE;
809 VUNSETATTR (var, att_invisible);
811 xfree (input_string);
815 /* This code implements the Posix.2 spec for splitting the words
816 read and assigning them to variables. */
817 orig_input_string = input_string;
819 /* Remove IFS white space at the beginning of the input string. If
820 $IFS is null, no field splitting is performed. */
821 for (t = input_string; ifs_chars && *ifs_chars && spctabnl(*t) && isifs(*t); t++)
824 for (; list->next; list = list->next)
826 varname = list->word->word;
827 #if defined (ARRAY_VARS)
828 if (legal_identifier (varname) == 0 && valid_array_reference (varname, 0) == 0)
830 if (legal_identifier (varname) == 0)
833 sh_invalidid (varname);
834 xfree (orig_input_string);
835 return (EXECUTION_FAILURE);
838 /* If there are more variables than words read from the input,
839 the remaining variables are set to the empty string. */
842 /* This call updates INPUT_STRING. */
843 t = get_word_from_string (&input_string, ifs_chars, &e);
846 /* Don't bother to remove the CTLESC unless we added one
847 somewhere while reading the string. */
850 t1 = dequote_string (t);
851 var = bind_read_variable (varname, t1);
855 var = bind_read_variable (varname, t ? t : "");
860 var = bind_read_variable (varname, "");
866 xfree (orig_input_string);
867 return (EXECUTION_FAILURE);
870 stupidly_hack_special_variables (varname);
871 VUNSETATTR (var, att_invisible);
874 /* Now assign the rest of the line to the last variable argument. */
875 #if defined (ARRAY_VARS)
876 if (legal_identifier (list->word->word) == 0 && valid_array_reference (list->word->word, 0) == 0)
878 if (legal_identifier (list->word->word) == 0)
881 sh_invalidid (list->word->word);
882 xfree (orig_input_string);
883 return (EXECUTION_FAILURE);
887 /* This has to be done this way rather than using string_list
888 and list_string because Posix.2 says that the last variable gets the
889 remaining words and their intervening separators. */
890 input_string = strip_trailing_ifs_whitespace (input_string, ifs_chars, saw_escape);
892 /* Check whether or not the number of fields is exactly the same as the
893 number of variables. */
898 t = get_word_from_string (&input_string, ifs_chars, &e);
899 if (*input_string == 0)
900 tofree = input_string = t;
903 input_string = strip_trailing_ifs_whitespace (t1, ifs_chars, saw_escape);
909 if (saw_escape && input_string && *input_string)
911 t = dequote_string (input_string);
912 var = bind_read_variable (list->word->word, t);
916 var = bind_read_variable (list->word->word, input_string ? input_string : "");
920 stupidly_hack_special_variables (list->word->word);
921 VUNSETATTR (var, att_invisible);
924 retval = EXECUTION_FAILURE;
927 xfree (orig_input_string);
933 bind_read_variable (name, value)
938 #if defined (ARRAY_VARS)
939 if (valid_array_reference (name, 0) == 0)
940 v = bind_variable (name, value, 0);
942 v = assign_array_element (name, value, 0);
943 #else /* !ARRAY_VARS */
944 v = bind_variable (name, value, 0);
945 #endif /* !ARRAY_VARS */
947 : ((readonly_p (v) || noassign_p (v)) ? (SHELL_VAR *)NULL : v));
950 #if defined (HANDLE_MULTIBYTE)
952 read_mbchar (fd, string, ind, ch, unbuffered)
955 int ind, ch, unbuffered;
957 char mbchar[MB_LEN_MAX + 1];
961 mbstate_t ps, ps_back;
964 memset (&ps, '\0', sizeof (mbstate_t));
965 memset (&ps_back, '\0', sizeof (mbstate_t));
969 for (n = 0; n <= MB_LEN_MAX; n++)
972 ret = mbrtowc (&wc, mbchar, i, &ps);
973 if (ret == (size_t)-2)
976 /* We don't want to be interrupted during a multibyte char read */
978 r = zread (fd, &c, 1);
986 else if (ret == (size_t)-1 || ret == (size_t)0 || ret > (size_t)0)
991 if (i > 1) /* read a multibyte char */
992 /* mbchar[0] is already string[ind-1] */
993 for (r = 1; r < i; r++)
994 string[ind+r-1] = mbchar[r];
1004 ttsetattr (ttp->fd, ttp->attrs);
1012 ttyrestore (&termsave);
1016 read_tty_modified ()
1018 return (tty_modified);
1021 #if defined (READLINE)
1022 static rl_completion_func_t *old_attempted_completion_function = 0;
1023 static rl_hook_func_t *old_startup_hook;
1024 static char *deftext;
1027 reset_attempted_completion_function (cp)
1030 if (rl_attempted_completion_function == 0 && old_attempted_completion_function)
1031 rl_attempted_completion_function = old_attempted_completion_function;
1040 if (old_startup_hook)
1041 r1 = (*old_startup_hook) ();
1044 r2 = rl_insert_text (deftext);
1045 deftext = (char *)NULL;
1046 rl_startup_hook = old_startup_hook;
1047 old_startup_hook = (rl_hook_func_t *)NULL;
1053 edit_line (p, itext)
1060 if (bash_readline_initialized == 0)
1061 initialize_readline ();
1063 old_attempted_completion_function = rl_attempted_completion_function;
1064 rl_attempted_completion_function = (rl_completion_func_t *)NULL;
1065 bashline_set_event_hook ();
1068 old_startup_hook = rl_startup_hook;
1069 rl_startup_hook = set_itext;
1075 rl_attempted_completion_function = old_attempted_completion_function;
1076 old_attempted_completion_function = (rl_completion_func_t *)NULL;
1077 bashline_reset_event_hook ();
1082 ret = (char *)xrealloc (ret, len + 2);
1088 static int old_delim_ctype;
1089 static rl_command_func_t *old_delim_func;
1090 static int old_newline_ctype;
1091 static rl_command_func_t *old_newline_func;
1093 static unsigned char delim_char;
1101 if (bash_readline_initialized == 0)
1102 initialize_readline ();
1103 cmap = rl_get_keymap ();
1105 /* Change newline to self-insert */
1106 old_newline_ctype = cmap[RETURN].type;
1107 old_newline_func = cmap[RETURN].function;
1108 cmap[RETURN].type = ISFUNC;
1109 cmap[RETURN].function = rl_insert;
1111 /* Bind the delimiter character to accept-line. */
1112 old_delim_ctype = cmap[c].type;
1113 old_delim_func = cmap[c].function;
1114 cmap[c].type = ISFUNC;
1115 cmap[c].function = rl_newline;
1121 reset_eol_delim (cp)
1126 cmap = rl_get_keymap ();
1128 cmap[RETURN].type = old_newline_ctype;
1129 cmap[RETURN].function = old_newline_func;
1131 cmap[delim_char].type = old_delim_ctype;
1132 cmap[delim_char].function = old_delim_func;